load("js/luajs/psbc_luaFunc.js")

/**
 *　用于匹配引号引起来的部分 局部匹配 故必须用find方法寻找匹配项 javascript:queryDetail('xxx','C','04','CNY','1','01','xxxx')
 */
var QUOTE_PARAMS_PATTERN = Pattern.compile("\\'([^\\']+)\\'");

var checkTime = 1;
//登录方式
var loginType;

/**
 * 匹配获取出账账单总页数
 */
var  PAGE_NUM = Pattern.compile("共(\\d+)页");

var t = 0;

var  monthBill = new HashMap();

/**
 * 匹配获取总记录数
 */
var RECORD_NUM = Pattern.compile("(\\d+)条");

var  interestMappings = new HashMap();
var tzck = new HashMap();
var cbcx = new HashMap();
var zczq = new HashMap();
var lczq = new HashMap();
var zclq = new HashMap();
var dhlb = new HashMap();
{
    tzck.put("一天", "0.0055");
    tzck.put("七天", "0.011");

    cbcx.put("一年", "0.0135");
    cbcx.put("三年", "0.0156");
    cbcx.put("五年", "0.0156");

    zczq.put("三个月", "0.0135");
    zczq.put("六个月", "0.0156");
    zczq.put("一年", "0.0178");
    zczq.put("二年", "0.0225");
    zczq.put("三年", "0.0275");
    zczq.put("五年", "0.0275");
    zczq.put("定活两便","0.00");

    lczq.put("一年", "0.0135");
    lczq.put("三年", "0.0156");
    lczq.put("五年", "0.0156");

    zclq.put("一年", "0.0135");
    zclq.put("三年", "0.0156");
    zclq.put("五年", "0.0156");

    dhlb.put("定活两便", "0.0035");

    interestMappings.put("活期", "0.003");
    interestMappings.put("通知存款", tzck);
    interestMappings.put("存本取息", cbcx);
    interestMappings.put("整存整取", zczq);
    interestMappings.put("零存整取", lczq);
    interestMappings.put("整存零取", zclq);
    interestMappings.put("定活两便", dhlb);
    interestMappings.put("协定存款", "0.01");
}
var unExistDebit = false;
var unExistCredit = false;

var isShiftOn = false;

var v6_psbc_java_funcs = {

    //打开首页
    openHomePage : function(){
        openLoginPage(checkTime);
        var firstLoginText = get_html();
        storeDataToFile(context, firstLoginText, "firstLoginText.html");
        context.put("login_html_result",firstLoginText);
    },

    //检查控件是否安装
    checkControlAvailable:function(){
        return Boolean.valueOf(checkControlAvailable())
    },

    //检查代理是否可用，是以正常登录成功之后找的页面元素为判断依据
    checkProxyAvailable: function () {
        var loginText = context.get("login_html_result");
        return StringUtils.isNotBlank(loginText) && equals(Jsoup.parse(loginText).select("#loginContent > div > div > div.cont-wraper > p").text(),  "个人网银登录")
    },

    checkTargetWebsiteAvailable:function () {
        return true;

    },

    //是否需要重置环境，比如图片验证码，代理错误等的情况是允许进行重试的
    needResetEnvironment:function(){
        return  equals(context.get("currentErrorCode"), BALO_99601_10) ||
            equals(context.get("currentErrorCode"),BALO_99601_30 ) ||
            equals(context.get("currentErrorCode"),BACR_99601_60)  ||
            equals(context.get("currentErrorCode"), BALO_99602_50);
    },

    //开始登录流程
    login: function () {

        //选择登录方式，邮储支持四中登录方式
        selectLoginType();

        //输入用户名和密码
        InputUsernameAndPassword();

        //输入图片验证码并且点击登录按钮
        inputImageAndLogin();

        //判断登录之后是哪个页面
        judgeLoginPage();

        //获取登录之后抓取页面的一些准备参数
        getNecessaryParameter();

        //获取cookie的值，是为了发送请求
        getCookieValue();

    },

    //登录成功之后的抓取流程
    crawl: function () {

        //抓取卡类型
        getCardList();

        //判断卡类型
        //judgeCardType();

        //判断是否为空
        judgeisEmpty();

        //借记卡数量解析
        debitCardSize();

        //信用卡数量解析
        creditCardSize();

        createData();
        var data_list = context.get(ALL_DATA);

        //抓取借记卡
        crawlDebit(data_list);
        
        //抓取信用卡
        crawlCredit(data_list);

        //creditCrawl();

        //选择卡类型
        //slectCardTypeAndCrawl();

        //对是最终知否存在卡进行判断
        if(unExistCredit&&unExistDebit){
            // throw new BankException(BankConstants.BALO_20304_30,BankConstants.errorMsgMap.get(BALO_20304_30));
            throwBankExceptionByErrorMsg("未获取到卡片信息，请登录官网绑定卡片");
        }
    },
    exitLogin :function () {},
    exit:function () {}
}



function crawlCredit(data_list) {

    if (context.get("psbc_is_exsit_credit_card") && context.get(keys.CRED_CARD_SIZE) > 0) {
        for (var i = 0; i < data_list.size(); i++) {

            var creditCardAllData = data_list.get(i);

            if (creditCardAllData.getCardType().equals("信用卡")) {

                getCreditCardInfoList(creditCardAllData);


                //抓取基本信息信息
                crawlCreditDepostInfo(creditCardAllData);

                //解析基本信息信息
                praseCreditBaseInfo(creditCardAllData);

                //抓取以及解析信用卡基本数据
                //getCreditCardDetailInfoList(creditCardAllData);

                //获取已出账单信息
                getDoneBillDetail(creditCardAllData);

                //获取未出账单信息
                getUndoneBillDetail(creditCardAllData);

                //统一计算newChargers
                //setNewCharges(creditCardAllData);

            }
        }
    }
    
}
function crawlDebit(data_list) {

    for (var i = 0; i < data_list.size(); i++) {
        try{
            var creditCardAllData = data_list.get(i);

            if (creditCardAllData.getCardType().equals("借记卡")) {
                //借记卡抓取
                logger.info("任务taskKey = {}, 开始抓取借记卡", context.get(LUA_TASK_KEY));

                getDebitCardInfoList(creditCardAllData);

                //抓取存款信息
                crawlDepositstInfo(creditCardAllData);

                //解析存款信息
                praseDepositsInfo(creditCardAllData);

                //getDebitCardDetailInfo(creditCardAllData);

                crawlAndPraseDebitBillInfo(creditCardAllData);

            }
        } catch ( e){
            statCaughtExceptionByJS(context, e);
            logger.error("任务taskKey = {}, 抓取借记卡异常{}", context.get(LUA_TASK_KEY), e);
        }
    }
}

/**
 * 判断是否为空
 */
function judgeisEmpty() {
    var cardList = JSON.parse(context.get("cardList"));
    var em = cardList.getString("em");

    logger.info("输出em的值{}",em);
    if(cardList==null  ||  ("会话已超时请重新登录").equals(cardList.getString("em"))){
        throw new BankException(BACR_99602_20, errorMsgMap.get(BACR_99602_20));
    }
    var cardNumList =  cardList.getJSONArray("iAccountInfoList");
    context.put("cardNumList",cardNumList);
}

function creditCardSize() {
    var cardNumList =context.get("cardNumList");
    var creditCount = 0;
    for each (var element in cardNumList) {
        var accountType = element.getString("accountType");
        if("07".equals( accountType)){
            creditCount = creditCount+1;
        }else{
            continue;
        }
        logger.info("输出卡类型{},{}",accountType,creditCount);
    }
    context.put("psbc_is_exsit_credit_card",true);
    context.put(keys.CRED_CARD_SIZE, creditCount);
}


function debitCardSize() {
    var cardNumList =context.get("cardNumList");
    var debitCount = 0;
    for each (var element in cardNumList) {
        var accountType = element.getString("accountType");
        if(!("07".equals( accountType))){
            debitCount= debitCount+1;
        }else{
            continue;
        }
        logger.info("输出卡类型{},{}",accountType,debitCount);
    }
    context.put(keys.DEBT_CARD_SIZE, debitCount);
}
function selectLoginType(){
    var loginTypeMappings = {
        IDCARD : "cerType",
        USERNAME : "logType",
        MOBILE : "mobType",
        CARDNO : "accType"
    }
    //选择登录方式
    loginType = context.get(LUA_TASK_LOGIN_TYPE);
    logger.info("邮储银行任务【 {} 】 ,选择的登录方式是【{}】", context.get(LUA_TASK_KEY) ,loginType);
    var chooseLoginTypeResult = chooseLoginType(loginTypeMappings[loginType]);
    var isChooseLoginTypeCorrectFunc = function (chooseLoginTypeResult) {
        return Boolean.valueOf(chooseLoginTypeResult);
    };
    var getChooseLoginTypeErrorMsg = function (chooseLoginTypeResult) {
        return "用户名未输入";
    };
    assertTrueOrThrowException(chooseLoginTypeResult, isChooseLoginTypeCorrectFunc, getChooseLoginTypeErrorMsg);
    logger.info("邮储银行任务【 {} 】 ,用户名选择成功，结果是【{}】", context.get(LUA_TASK_KEY), chooseLoginTypeResult);

}

function InputUsernameAndPassword(){
    //显示窗口输入密码
    var loginText;
    if(loginType.equals("IDCARD")){
        loginText = getLoginParams(context)[0].toUpperCase();
    }else{
        loginText = getLoginParams(context)[0];
    }

    var passWord = context.get(LUA_TASK_TOKEN);
    var inputUPresult = inputUPAndGetOperationResult(loginText, passWord)
    var pwdPath = get_picture_gs();
    logger.info("邮储银行 taskKey: {}   截图-路径: {}",  context.get(LUA_TASK_KEY), pwdPath);

    var isInputUPResultCorrectFunc = function (inputUPresult) {
        return Boolean.valueOf(inputUPresult)
    };
    var getInputUPResultErrorMsg = function (inputUPresult) {
        return "密码因控件输入错误";
    };
    assertTrueOrThrowException(inputUPresult, isInputUPResultCorrectFunc, getInputUPResultErrorMsg);
    logger.info("邮储银行任务【 {} 】 密码输入：{}", context.get(LUA_TASK_KEY), Boolean.valueOf(inputUPresult) ? "成功" : "失败");
}

function inputImageAndLogin(){
    var getImagePathResult = JSON.parse(clickImgAndGetImgPath())

    var isGetImagePathCorrectFunc = function(getImagePathResult) {
        return Boolean.valueOf(getImagePathResult.get("flag"))
    }

    var getGetImagePathErrorMsgFunc = function(getImagePathResult) {
        return "图片验证码获取失败"
    }
    assertTrueOrThrowException(getImagePathResult, isGetImagePathCorrectFunc, getGetImagePathErrorMsgFunc)
    logger.info("邮储银行任务【 {} 】 图片路径获取成功", context.get(LUA_TASK_KEY));

    var contentWillBeCheckedFunc = function(){
        var imagePath = preHandleImage(getImagePathResult.get("path"))
        logger.info("任务【 {} 】图片验证码路径【 {} 】", context.get(LUA_TASK_KEY), imagePath)

        context.put(TASK_IMG_PATH, imagePath);
        context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");

        return waitImgCodeBySecondsByJs(context, 60, true, 3)
    }

    var isCorrectFunc = function(contentWillBeChecked){
        return contentWillBeChecked.length === 4
    }

    var getErrorMsgFunc = function(contentWillBeChecked){
        return "图片验证码错误"
    }

    repeaterAndAssertTrueOrThrowException(contentWillBeCheckedFunc, isCorrectFunc, getErrorMsgFunc, 3)

    inputImgAndClickLoginButton(_context['contentWillBeChecked']);

    var imagePath = getScreenShots();
    logger.info("邮储银行 taskKey=" + context.get(Constants.LUA_TASK_KEY) + " 登录截图路径 " + imagePath);
}


function judgeLoginPage() {
    var pageCheckResult = JSON.parse(whichPage())

    var loginAfterIsBlank = get_html2();
    storeDataToFile(context, loginAfterIsBlank, "loginAfterIsBlank.html");
    logger.info("输出登录之后的结果{}",(Jsoup.parse(loginAfterIsBlank).select("#welMes").text()).indexOf("您好") != -1);
    var loginPageView = get_picture_gs();
    logger.info("{},截取未出账单页面保存截图路径:{}",context.get(LUA_TASK_KEY),loginPageView);

    if(loginAfterIsBlank.contains("非柜台签约客户认证") ){
        var feiQianYue = get_html2();
        storeDataToFile(context, feiQianYue, "feiQianYue.html");
        logger.info("任务【 {} 】 ,登录之后显示的页面是非签约客户页面", context.get(LUA_TASK_KEY))
        throwBankExceptionByErrorCode(BALO_22101_10);
    }else if(!(Jsoup.parse(loginAfterIsBlank).select("#welMes").text()).indexOf("您好") != -1 ){
        for (var i = 1; i<= 5 ;i++) {
            if((Jsoup.parse(loginAfterIsBlank).select("#welMes").text()).indexOf("您好") != -1){
                var a = (Jsoup.parse(loginAfterIsBlank).select("#welMes").text()).indexOf("您好") != -1;
                logger.info("任务号 taskkey 【{}】输出页面是否正常{}",context.get(Constants.LUA_TASK_KEY),a);
                break;
            }else if (i==6){
                logger.info("任务【 {} 】，新出现的错误2",context.get(LUA_TASK_KEY))
                throwBankExceptionByErrorCode(BACR_99601_60)
            }else{
                var loginAfterIsBlank = get_html2();
                storeDataToFile(context, loginAfterIsBlank, "loginAfterIsBlank.html");
                Thread.sleep(1000);
            }
        }
        var pageCheckResult = JSON.parse(whichPage())
        if(Boolean.valueOf(pageCheckResult.get("isContractedUser")) ){
            logger.info("任务【 {} 】 ,登录之后显示的页面是非签约客户页面", context.get(LUA_TASK_KEY))
            throwBankExceptionByErrorCode(BALO_22101_10);
        }else if(Boolean.valueOf(pageCheckResult.get("isLoginPage"))){
            handleLoginError()
        }else if(Boolean.valueOf(pageCheckResult.get("isLoginSuccess"))){
            logger.info("任务【 {} 】 ,登录成功", context.get(LUA_TASK_KEY));
        }else if(StringUtils.isNotBlank(loginAfterIsBlank) && loginAfterIsBlank.contains("登录密码修改") ){
            logger.info("任务【 {} 】 ,登录之后显示的页面是登录密码修改页面", context.get(LUA_TASK_KEY))
            throwBankExceptionByErrorCode(BALO_22004_10);
        }else if(Boolean.valueOf(JSON.parse(firstLogin()).get("isFirstLogin"))){
            logger.info("任务【 {} 】 ,首次登录页面", context.get(LUA_TASK_KEY))
            throwBankExceptionByErrorCode(BALO_22106_10);
        }else {
            logger.info("任务【 {} 】，新出现的错误2",context.get(LUA_TASK_KEY))
            throwBankExceptionByErrorCode(BACR_99601_60)
        }

    }else if(Boolean.valueOf(pageCheckResult.get("isLoginPage"))){
        handleLoginError()
    }else if(Boolean.valueOf(pageCheckResult.get("isLoginSuccess"))){
        logger.info("任务【 {} 】 ,登录成功", context.get(LUA_TASK_KEY));
    } else if(StringUtils.isNotBlank(loginAfterIsBlank) && loginAfterIsBlank.contains("登录密码修改") ){
        logger.info("任务【 {} 】 ,登录之后显示的页面是登录密码修改页面", context.get(LUA_TASK_KEY))
        throwBankExceptionByErrorCode(BALO_22004_10);
    }else if(Boolean.valueOf(JSON.parse(firstLogin()).get("isFirstLogin"))){
        logger.info("任务【 {} 】 ,首次登录页面", context.get(LUA_TASK_KEY))
        throwBankExceptionByErrorCode(BALO_22106_10);
    }else {
        logger.info("任务【 {} 】，新出现的错误2",context.get(LUA_TASK_KEY))
        throwBankExceptionByErrorCode(BACR_99601_60)
    }

}

function judgeCardType() {

    var cardList = JSON.parse(context.get("cardList"));
    var em = cardList.getString("em");

    logger.info("输出em的值{}",em);
    if(cardList==null  ||  ("会话已超时请重新登录").equals(cardList.getString("em"))){
        throw new BankException(BACR_99602_20, errorMsgMap.get(BACR_99602_20));
    }
    var cardNumList =  cardList.getJSONArray("iAccountInfoList");
    var  accountType;

    createData();
    var data_list = context.get(ALL_DATA)


    var creditCount = 0;
    for each (var element in cardNumList) {
        accountType = element.getString("accountType");
        if("07".equals( accountType)){
            try{
                //抓取信用卡
                logger.info("任务taskKey = {}, 开始抓取信用卡", context.get(LUA_TASK_KEY));
                creditCrawl();
            } catch (e){
                statCaughtExceptionByJS(context, e);
                logger.error("任务taskKey = {}, 抓取信用卡异常{}", context.get(LUA_TASK_KEY), e);
            }

        }else{
            continue;
        }
        creditCount = creditCount+1;
        context.put("psbc_is_exsit_credit_card", true);
        context.put(keys.CRED_CARD_SIZE, creditCount);
        logger.info("输出卡类型{},{}",accountType,creditCount);
    }

    var debitCount = 0;

    for each (var element in cardNumList) {
        accountType = element.getString("accountType");
        if(!("07".equals( accountType))){
            try{
                //借记卡抓取
                logger.info("任务taskKey = {}, 开始抓取借记卡", context.get(LUA_TASK_KEY));
                debitCrawl();
            } catch ( e){
                statCaughtExceptionByJS(context, e);
                logger.error("任务taskKey = {}, 抓取借记卡异常{}", context.get(LUA_TASK_KEY), e);
            }

        }else{
            continue;
        }
        debitCount= debitCount+1;
        logger.info("输出卡类型{},{}",accountType,debitCount);
    }

    //对是最终知否存在卡进行判断
    if(unExistCredit&&unExistDebit){
        // throw new BankException(BankConstants.BALO_20304_30,BankConstants.errorMsgMap.get(BALO_20304_30));
        throwBankExceptionByErrorMsg("未获取到卡片信息，请登录官网绑定卡片");
    }

}

function slectCardTypeAndCrawl(accountType) {

    //去除卡类型判断的结果，07代表信用卡
   // var accountType = context.get("accountType");
    //信用卡抓取
    if(("07").equals(accountType)){
        try{
            //抓取信用卡
            logger.info("任务taskKey = {}, 开始抓取信用卡", context.get(LUA_TASK_KEY));
            creditCrawl();
        } catch (e){
            statCaughtExceptionByJS(context, e);
            logger.error("任务taskKey = {}, 抓取信用卡异常{}", context.get(LUA_TASK_KEY), e);
        }
    }else{
        try{
            //借记卡抓取
            logger.info("任务taskKey = {}, 开始抓取借记卡", context.get(LUA_TASK_KEY));
            debitCrawl();
        } catch ( e){
            statCaughtExceptionByJS(context, e);
            logger.error("任务taskKey = {}, 抓取借记卡异常{}", context.get(LUA_TASK_KEY), e);
        }
    }
}

function getNecessaryParameter() {
    var getEmpSIDResult = JSON.parse(getEmpSID())
    var isGetEmpSIDCorrectFunc = function(getEmpSIDResult){
        return Boolean.valueOf(getEmpSIDResult.get("flag"))
    }

    var getEmpSIDErrorMsgFunc = function (getEmpSIDResult) {
        return "登录超时"
    }
    assertTrueOrThrowException(getEmpSIDResult,isGetEmpSIDCorrectFunc,getEmpSIDErrorMsgFunc);
    logger.info("邮储任务taskKey = {}, 获取登录之后的EMP_SID为{}", context.get(LUA_TASK_KEY), getEmpSIDResult.get("empSID"));


    var getCustNoSIDResult = JSON.parse(getCustNo());

    var isGetEmpSIDCorrectFunc = function(getCustNoSIDResult){
        return Boolean.valueOf(getCustNoSIDResult.get("flag"))
    }

    var getEmpSIDErrorMsgFunc = function (getCustNoSIDResult) {
        return "登录超时"
    }
    assertTrueOrThrowException(getCustNoSIDResult,isGetEmpSIDCorrectFunc,getEmpSIDErrorMsgFunc);
    logger.info("邮储任务taskKey = {}, 获取登录之后的CustNo为{}", context.get(LUA_TASK_KEY), getCustNoSIDResult.get("custNo"));

    var getRandomIDResult = JSON.parse(getRandomID());
    var isGetRandomIDCorrectFunc = function(getRandomIDResult){
        return Boolean.valueOf(getRandomIDResult.get("flag"))
    }

    var getRandomIDErrorMsgFunc = function (getRandomIDResult) {
        return "登录超时"
    }
    assertTrueOrThrowException(getRandomIDResult,isGetRandomIDCorrectFunc,getRandomIDErrorMsgFunc);
    logger.info("邮储任务taskKey = {}, 获取登录之后的randomID为{}", context.get(LUA_TASK_KEY), getRandomIDResult.get("randomID"));

    //获取windowId

    var getWindowIdResult = JSON.parse(getWindowId());
    var windowId =getWindowIdResult.get("windowId").replaceAll("trans-window-frame_item","");
    logger.info("邮储任务taskKey = {}, 获取登录之后的windowId为{}", context.get(LUA_TASK_KEY), windowId);
    var isGetWindowIdCorrectFunc = function(getWindowIdResult){
        return Boolean.valueOf(getWindowIdResult.get("flag"))
    }

    var getWindowIdErrorMsgFunc = function (getWindowIdResult) {
        return "登录超时"
    }
    assertTrueOrThrowException(getWindowIdResult,isGetWindowIdCorrectFunc,getWindowIdErrorMsgFunc);




    //获取mvcId

    var getMcvIdResult = JSON.parse(getMcvId());

    var isGetMcvIdCorrectFunc = function(getMcvIdResult){
        return Boolean.valueOf(getWindowIdResult.get("flag"))
    }

    var getMcvIdErrorMsgFunc = function (getMcvIdResult) {
        return "登录超时"
    }
    assertTrueOrThrowException(getMcvIdResult,isGetMcvIdCorrectFunc,getMcvIdErrorMsgFunc);
    logger.info("邮储任务taskKey = {}, 获取登录之后的mvcId为{}", context.get(LUA_TASK_KEY), getMcvIdResult.get("mcvId"));


    context.put("empSID", getEmpSIDResult.get("empSID"))
    context.put("randomID", getRandomIDResult.get("randomID"));
    context.put("custNo", getCustNoSIDResult.get("custNo"));
    context.put("mcvId", getCustNoSIDResult.get("mcvId"));
    context.put("windowId", windowId);
}

function getCookieValue() {

    var cookiesResult = getLoginCookie();
    var cookies = JSON.parse(cookiesResult).getString("cookie");
    var isGetMcvIdCorrectFunc = function(cookiesResult){
        return !("empty").equals(cookiesResult);
    }

    var getMcvIdErrorMsgFunc = function (cookiesResult) {
        return "登录超时"
    }
    assertTrueOrThrowException(cookies,isGetMcvIdCorrectFunc,getMcvIdErrorMsgFunc);
    logger.info("邮储任务taskKey = {}, 获取登录之后的cookie为{}", context.get(LUA_TASK_KEY), cookies);
    context.put("cookies", cookies);
}
/**
 * 获取已出账单路径
 */
function getDoneBillDetailUrl() {
    var requestParams = new LinkedHashMap();
    /*EMP_SID	BSFJGIDFJECFCCIJIRBCEUCIJPGUBLISJJHQBXAN
     responseFormat	JSON
     IS_BATCH_DOWN_FLAG	1
     currentBusinessCode	00844001
     accountNo	6259190202618751
     currencyFlag	L
     billTime	1712
     isInLast6Months	0*/
    var doneBilDetaillurl = "https://pbank.psbc.com/perbank/creditCardBill_billDetailDownload.do";
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("IS_BATCH_DOWN_FLAG","1");
    requestParams.put("currentBusinessCode","00841001");
    requestParams.put("accountNo","6259190202618751");
    requestParams.put("currencyFlag","L");
    requestParams.put("billTime","1712");
    requestParams.put("isInLast6Months","0");

    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var doneDetalHtml = RequestUtil.postAsFile("D:\\htmlStorage\\BANK\\doneBilDetaill.xls",doneBilDetaillurl, requestParams, header);
    logger.info("任务【 {} 】 ,获取卡列表结果【 {} 】", context.get(LUA_TASK_KEY), doneDetalHtml);
    storeDataToFile(context, doneDetalHtml, "credit_card_Done_imfo.html");
}
/**
 * 获取信用卡depost
 */
function crawlCreditInfo (cardNum,cardSize) {
    var  cardDetailInfoUrl = "https://pbank.psbc.com/perbank/creditCardAcctQuery_queryHostDetail.do";
    var requestParams = new LinkedHashMap();
    requestParams.put("currentBusinessCode","00841001");
    requestParams.put("accountNo",cardNum);
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("RANDOM_ID",context.get("randomID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("channel","1101");
    requestParams.put("version","stanver");


    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var depostListHtml = JSON.parse(RequestUtil.post(cardDetailInfoUrl, requestParams, header));
    storeDataToFile(context, depostListHtml, "credit_"+cardSize+"_card_detail_info.html");
    context.put("depostListHtml",depostListHtml);
}
/**
 * 查询交易明细按钮
 */
function getDebitInfo (start,end,index,cardNum) {
    var body = new LinkedHashMap();
    body.put("accNo", "00000504");
    body.put("accountNo", cardNum);
    body.put("beginDate", start);
    body.put("bkBookFlg", "2");
    body.put("channel", "1101");
    body.put("currentBusinessCode", "00312000");
    body.put("EMP_SID", context.get("empSID"));
    body.put("endDate", end);
    body.put("inOut", "0");
    body.put("RANDOM_ID", context.get("randomID"));
    body.put("responseFormat", "JSON");
    body.put("tranType", "1");
    body.put("turnPageBeginPos","1" );
    body.put("turnPageShowNum", "10");
    body.put("version", "stanver");

    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");
    var actTrsInfoQryUrl = "https://pbank.psbc.com/perbank/dealDetailQuery.do";
    //查询交易明细
    var debitInfo = JSON.parse(RequestUtil.post(actTrsInfoQryUrl, body, header));
    storeDataToFile(context, debitInfo, ""+index+"debit_card_bill_info.html");
    return debitInfo;
}
/**
 * 为下载做准备
 */
function needParameters() {
    var body = new LinkedHashMap();
    body.put("currentBusinessCode", "00000504");
    body.put("EMP_SID", context.get("empSID"));
    body.put("RANDOM_ID", context.get("randomID"));
    body.put("responseFormat","JSON");
    body.put("channel","1101");
    body.put("version","stanver");

    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");
    var beforeDetaiDown = "https://pbank.psbc.com/perbank/queryAllAccounts.do";
    //查询交易明细
    var beforeDetaiDownInfo = JSON.parse(RequestUtil.post(beforeDetaiDown, body, header));
    storeDataToFile(context, beforeDetaiDownInfo, "beforeDetaiDownInfo.html");
    return beforeDetaiDownInfo;
}
/**
 * 消费明细下载
 */
function detaiDown(start,end,cardNum) {

    var body = new LinkedHashMap()
    body.put("EMP_SID", context.get("empSID"));
    body.put("responseFormat", "JSON");
    body.put("currentBusinessCode", "00312000");
    body.put("turnPageBeginPos","1" );
    body.put("turnPageShowNum", "10");
    body.put("tranType", "1");
    body.put("beginDate", start);
    body.put("endDate", end);
    body.put("inOut", "0");
    body.put("accNo", "00000504");
    body.put("accountNo", cardNum);
    body.put("bkBookFlg", "2");
    body.put("custNo", context.get("custNo"));

    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");
    var BillDownUrl = "https://pbank.psbc.com/perbank/detailDown.do";
    //查询交易明细
    //D:\htmlStorage\BANK\18\06\25\18062514CREDHNkNJXc2
    //18062811CREDbacWp46fh
    var taskey = context.get(LUA_TASK_KEY);
    var year =taskey.substring(0,2);
    var mounth =taskey.substring(2,4);
    var date =taskey.substring(4,6);
    var BillDownHtml = RequestUtil.postAsFile("D:\\htmlStorage\\BANK\\"+year+"\\"+mounth+"\\"+date+"\\"+taskey+"\\debit"+start+"BillInfo.xls",BillDownUrl, body, header);
    var billDownUrl = BillDownHtml.getPath();
    logger.info("任务【 {} 】 ,获取卡列表结果【 {} 】", context.get(LUA_TASK_KEY), BillDownHtml);
    storeDataToFile(context, BillDownHtml, start+"debit_card_bill_html");
    context.put("billDownUrl",BillDownHtml);
}

/*function depostList() {
    var  cardDetailInfoUrl = "https://pbank.psbc.com/perbank/queryBHQSubAcc.do";
    var requestParams = new LinkedHashMap();
    requestParams.put("accNo","6221871000003832849");
    requestParams.put("pwdFlag","0");
    requestParams.put("bkBookFlg","2");
    requestParams.put("currentBusinessCode","00311000");
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("RANDOM_ID",context.get("randomID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("channel","1101");
    requestParams.put("version","stanver");


    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var depostListHtml = JSON.parse(RequestUtil.post(cardDetailInfoUrl, requestParams, header));
    storeDataToFile(context, depostListHtml, "debit_card_detail_info.html")
    logger.info("任务【 {} 】 ,获取卡列表结果【 {} 】", context.get(LUA_TASK_KEY), depostListHtml);
    context.put("cardList", depostList)
}*/
function getCardList() {

    var contentWillBeCheckedFunc = function(){
        var url = "https://pbank.psbc.com/perbank/queryAllAccounts.do";
        var body = new LinkedHashMap()
        body.put("currentBusinessCode", "00000504");
        body.put("EMP_SID", context.get("empSID"));
        body.put("RANDOM_ID", context.get("randomID"));
        body.put("responseFormat", "JSON");
        body.put("channel", "1101");
        body.put("version", "stanver");

        var header = new LinkedHashMap();
        header.put("Cookie", context.get("cookies"));
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");
        var cardList = RequestUtil.post(url, body, header);
        //var cardList = JSON.parse(FileUtils.readFileToString(new File("C:\\Users\\Administrator\\Desktop\\cardList.html")));

        storeDataToFile(context, cardList, "cardList.html");
        logger.info("任务【 {} 】 ,获取卡列表结果【 {} 】", context.get(LUA_TASK_KEY), cardList);
        context.put("cardList", cardList);

    }

    var isCorrectFunc = function(contentWillBeChecked){
        var cardList = context.get("cardList");
        var em = JSON.parse(cardList).getString("em");
        logger.info("邮储银行任务号taskKey = {}，判断当前卡号时候有列表，是否是会话超时，{},{}",context.get(LUA_TASK_KEY),em,StringUtils.isBlank(em));
        return StringUtils.isBlank(em);
    }

    var getErrorMsgFunc = function(contentWillBeChecked){
        return "消费明细获取失败";
    }

    repeaterAndAssertTrueOrThrowException(contentWillBeCheckedFunc, isCorrectFunc, getErrorMsgFunc, 3)

}
function typeMobile(){
    var questions = new ArrayList();
    questions.add("非签约用户需要要手机号才能继续登录，您的手机号是?")
    context.put(TASK_QUESTIONS, questions);
    var answerList = waitAnswerBySeconds(context, 120)


    setMobile(answerList[0])

    var mobileNoCheckResult = checkIfInput("mobileNo", answerList[0])

    var isMobileNoInputCorrectFunc = function(mobileNoCheckResult) {
        return Boolean.valueOf(mobileNoCheckResult)
    }

    var getMobileNoInputErrorMsgFunc = function(mobileNoCheckResult) {
        return "手机号未正确输入"
    }
    assertTrueOrThrowException(mobileNoCheckResult, isMobileNoInputCorrectFunc, getMobileNoInputErrorMsgFunc)
    logger.info("任务【 {} 】手机号输入成功【 {} 】", context.get(LUA_TASK_KEY), answerList[0])

}

function sendSms(){
    var smsSendResult = JSON.parse(sendMessage())
    var isSendSmsCorrectFunc = function(smsSendResult){
        return !Boolean.valueOf(smsSendResult.get("flag"))
    }

    var sendSmsGetErrorMsgFunc = function (smsSendResult) {
        return smsSendResult.get("errorMsg")
    }
    assertTrueOrThrowException(smsSendResult,isSendSmsCorrectFunc,sendSmsGetErrorMsgFunc);
    logger.info("任务【 {} 】短信验证码发送成功【 {} 】", context.get(LUA_TASK_KEY), smsSendResult)

}

function typeReceivedSms(){

    // 等待短信验证码
    var smsCode = waitSmsCodeBySeconds(context, 120);
    set_input_text_by_id("mobileVerifyCode", smsCode)

    var mobileVerifyCodeCheckResult = checkIfInput("mobileVerifyCode", smsCode)

    var isMobileVerifyCodeInputCorrectFunc = function(mobileVerifyCodeCheckResult) {
        return Boolean.valueOf(mobileVerifyCodeCheckResult)
    }

    var getMobileVerifyCodeInputErrorMsgFunc = function(mobileVerifyCodeCheckResult) {
        return "短信验证码错误"
    }
    assertTrueOrThrowException(mobileVerifyCodeCheckResult, isMobileVerifyCodeInputCorrectFunc, getMobileVerifyCodeInputErrorMsgFunc)
    logger.info("任务【 {} 】短信验证码输入成功【 {} 】", context.get(LUA_TASK_KEY), smsCode)
}

function handleLoginError(){
    var errorMsgCheckResult = JSON.parse(checkLoginErrorMsg());
    logger.info("邮储获取页面错误信息{}",errorMsgCheckResult);

    var isNoErrorMsgFunc = function (errorMsgCheckResult) {
        return !Boolean.valueOf(errorMsgCheckResult.get("flag"));
    }

    //检查登陆出现的错误信息
    var getLoginErrorMsgFunc = function(errorMsgCheckResult) {
        if(("无错误").equals(errorMsgCheckResult.get("errorMsg"))){
            return "登录超时";
        }
        return errorMsgCheckResult.get("errorMsg");
    }

    //断言
    assertTrueOrThrowException(errorMsgCheckResult, isNoErrorMsgFunc, getLoginErrorMsgFunc)
}

/**
 * 预处理图片 去除邮储验证码上的黑色数字和字母，只保留红色
 *
 * @param imagePath
 * @return
 * @throws Exception
 */
function preHandleImage(imagePath) {
    try {
        var rgb = new Array();
        var sourceImg = ImageIO.read(new File(imagePath));

        var width = sourceImg.getWidth();
        var height = sourceImg.getHeight();
        var minx = sourceImg.getMinX();
        var miny = sourceImg.getMinY();
        for (var i = minx; i < width; i++) {
            for (var j = miny; j < height; j++) {
                var pixel = sourceImg.getRGB(i, j); // 下面三行代码将一个像素转换为RGB数字
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                if (rgb[0] < 120 && rgb[1] < 120 && rgb[2] < 120) {
                    sourceImg.setRGB(i, j, 0xEECBAD);
                }
            }
        }
        var targetImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        targetImage.getGraphics().drawImage(sourceImg, 0, 0, width, height, null); //画图
        ImageIO.write(targetImage, "jpg", new File(imagePath));
    } catch (e) {
        statCaughtExceptionByJS(context, e);
        logger.error("邮储银行的验证码在获取时出错，taskKey:{}", context.get(LUA_TASK_KEY), e);
    }
    return imagePath;
}

/**
 * 判断登录状态
 */
function checkLoginStatus(loginErrorMsg){
    if (loginErrorMsg.contains("用户名或密码错误")) {
        logger.info("邮储银行用户名密码验证未通过，taskKey:{}", context.get(LUA_TASK_KEY));
        return "用户名或密码错误";
    } else if (loginErrorMsg.contains("验证码错误") || loginErrorMsg.contains("验证码过期")) {
        logger.info("邮储银行图片验证码验证未通过，taskKey:{}", context.get(LUA_TASK_KEY));
        return "图片验证码错误";

    } else if (loginErrorMsg.contains("当日登录密码输入错误次数超限，请次日再试")) {
        logger.info("邮储银行当日登录密码输入错误次数超限，请次日再试，taskKey:{}", context.get(LUA_TASK_KEY));
        return "当日登录密码输入错误次数超限，请次日再试";

    } else if (loginErrorMsg.contains("密码至少需要六位")) {
        logger.info("邮储银行密码至少需要六位，taskKey:{}", context.get(LUA_TASK_KEY));
        return "密码至少需要六位";

    } else if (loginErrorMsg.contains("用户登录id不符合要求格式")) {
        logger.info("邮储银行用户登录id不符合要求格式，taskKey:{}", context.get(LUA_TASK_KEY));
        return "用户登录id不符合要求格式";
    } else if (loginErrorMsg.contains("邮储银行由于您长时间未操作，为保障您的资金安全，请点击电脑键盘F5键刷新页面后重新")) {
        logger.info("邮储银行 长时间未操作请刷新页面，taskKey:{}", context.get(LUA_TASK_KEY));
        return "邮储银行由于您长时间未操作，为保障您的资金安全，请点击电脑键盘F5键刷新页面后重新";

    } else if (loginErrorMsg.contains("密码已锁定")) {
        logger.info("邮储银行 密码已锁定，taskKey:{}", context.get(LUA_TASK_KEY));
        return "密码已锁定";

    } else if (loginErrorMsg.contains("密码不符合要求格式")) {
        logger.info("邮储银行 密码已锁定，taskKey:{}", context.get(LUA_TASK_KEY));
        return "密码不符合要求格式";

    }else if (loginErrorMsg.contains("网银服务已暂停，请先进行恢复")) {
        logger.info("邮储银行 网银服务已暂停，请先进行恢复，taskKey:{}", context.get(LUA_TASK_KEY));
        return "网银服务已暂停，请先进行恢复";

    }else if (loginErrorMsg.contains("服务器无效响应")) {
        logger.info("邮储银行 网银服务已暂停，请先进行恢复，taskKey:{}", context.get(LUA_TASK_KEY));
        return "服务器无效响应";

    }else if (loginErrorMsg.contains("您当前只能使用用户名登录")) {
        logger.info("邮储银行 您当前只能使用用户名登录，taskKey:{}", context.get(LUA_TASK_KEY));
        return "您当前只能使用用户名登录";
    } else {
        logger.info("邮储银行登录错误信息：{}，taskKey:{}", loginErrorMsg, context.get(LUA_TASK_KEY));
        return loginErrorMsg;
    }
}



/**
 * 信用卡抓取
 *
 * @throws Exception
 */
function creditCrawl(){
    try{
        //创建集合存放多张信用卡
        var creditCardAllData = data_list.get(i);

        //获取基本信息
        getCreditCardInfoList(creditCardAllData);

        //判断是否存在数据
        if (creditCardAllDataList.size() > 0) {

            //抓取以及解析信用卡基本数据
            getCreditCardDetailInfoList(creditCardAllDataList);

            //获取已出账单信息
            getDoneBillDetail(creditCardAllDataList);

            //获取未出账单信息
            getUndoneBillDetail(creditCardAllDataList);

            //统一计算newChargers
            setNewCharges(creditCardAllDataList);

            //将抓取到的信息存入到上下文中
            context.put("credit_data", creditCardAllDataList);

        } else {
            logger.info("账户内不存在信用卡，taskKey = {}", context.get(LUA_TASK_KEY));
            unExistCredit = true;
        }
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡异常{}", context.get(LUA_TASK_KEY), e);
    }


}

/**
 * 获取信用卡未出账账单
 *
 * @param creditCardAllDataList
 * @throws ParseException
 */
function getUndoneBillDetail(creditCardAllData){
    try{

        var undoneBillDetailPath = get_picture_gs();
        logger.info("{},截取未出账单页面保存截图路径:{}",context.get(LUA_TASK_KEY),undoneBillDetailPath);
        logger.info("开始抓取未出账单任务号taskKey = {}",context.get(LUA_TASK_KEY));
        var creditUndoneBillDetailHtml = get_html2();
        storeDataToFile(context, creditUndoneBillDetailHtml, "creditUndoneBillDetail.html");
        var billAllData = getUNDoneBillAllDataHeaderData(creditCardAllData);
        var fullCardNum = creditCardAllData.getFullCardNum();
        getUndoneBillDetailUrl(fullCardNum);
        var expenses = new ArrayList();
        addBillHeaderInfo(expenses,"UNDONE",billAllData,getUndoneBillMonth().replaceAll("20",""));
        //expenseIFexist(expenses,"UNDONE",billAllData,getUndoneBillMonth().replaceAll("20",""));
        parseBillDetailInfo(expenses, "UNDONE" ,billAllData);
        //creditCardAllData.getBills().add(billAllData);


    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡getUndoneBillDetail方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }

}
/**
 * 判断是否有已出账单信息
 *
 */
function getIfBillDetailUrl() {
    var requestParams = new LinkedHashMap();
    /*currentBusinessCode	00841001
     accountNo	6259190202618751
     EMP_SID	JQEDIKGHCUDSBOHKGJDNBNCSHPAZIZCYHOELAZBI
     RANDOM_ID	0.9796297614743925
     responseFormat	JSON
     channel	1101
     version	stanver*/
    var url = "https://pbank.psbc.com/perbank/creditCardAcctQuery_queryBill.do";
    requestParams.put("currentBusinessCode","00841001");
    requestParams.put("accountNo","6259190202618751");
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("RANDOM_ID",context.get("randomID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("channel","1101");
    requestParams.put("version","stanver");


    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var depostListHtml = JSON.parse(RequestUtil.post(url, requestParams, header));
    storeDataToFile(context, depostListHtml, "debit_card_detail_info.html");
}
/**
 *获取已出账单url
 */
function   getUndoneBillDetailUrl(fullCardNum) {

    var body = new LinkedHashMap()
    body.put("EMP_SID", context.get("empSID"));
    body.put("responseFormat", "JSON");
    body.put("IS_BATCH_DOWN_FLAG", "1");
    body.put("currentBusinessCode","00843001" );
    body.put("accountNo", fullCardNum);
    body.put("currencyType", "L");

    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");
    var UnDoneBillDatilUrl = "https://pbank.psbc.com/perbank/creditCardNotYetBill_download.do";
    //查询交易明细
    //D:\htmlStorage\BANK\18\06\25\18062514CREDHNkNJXc2
    var taskey = context.get(LUA_TASK_KEY);
    var year =taskey.substring(0,2);
    var mounth =taskey.substring(2,4);
    var date =taskey.substring(4,6);
    var undoneDetalHtml = RequestUtil.postAsFile("D:\\htmlStorage\\BANK\\"+year+"\\"+mounth+"\\"+date+"\\"+taskey+"\\"+fullCardNum+"_"+"UndoneBillDetal.xls",UnDoneBillDatilUrl, body, header);
    var undoneDetalPath = undoneDetalHtml.getPath();
    logger.info("任务【 {} 】 ,获取卡列表结果【 {} 】", context.get(LUA_TASK_KEY), undoneDetalPath);
    storeDataToFile(context, undoneDetalHtml, fullCardNum+"_"+"credit_card_undone_imfo.html");
    context.put("doneDetalFile",undoneDetalHtml);
}

/**
 * 判断当前日期是否在账单日之前 未出账账单取上月月份 否则取下个月月份
 * 邮储银行出账单在账单日的22点，若当前时间在账单日22点前，则仍为未出账账单 账单月为当前月
 * 若在22点后未出账单账单月为下个月
 * https://www.51credit.com/creditcard/xueyuan/xykkp/11249993.shtml
 *
 * @return
 * @throws ParseException
 */
function getUndoneBillMonth(){
    var billmonth;
    var date1 = DateUtil.date();
    var  time = DateUtil.today().replaceAll("-","").substring(6,8);
    var day = parseInt(time);
    if(day <= Integer.valueOf(context.get("billDay")) && day <= 22){
    }else
    {
        DateUtil.offset(date1, DateField.MONTH, 1);
    }
    billmonth = DateUtil.format(date1, "yyyy-MM");
    logger.info("输出日期比对的结果{}",billmonth);
    return billmonth;



    /* var billMonth;
     var calendar = Calendar.getInstance();
     //今天的日期和账单日期进行比较，如果今天的日期小于每月的账单日期就认为是未出账单
     if (calendar.get(Calendar.DAY_OF_MONTH) <= Integer.valueOf(context.get("billDay")) && calendar.get(Calendar.DAY_OF_MONTH) <=  22) {
     } else {
     calendar.add(Calendar.MONTH, 1);
     }
     billMonth = yyyy_MM_FORMAT.format(calendar.getTime());
     return billMonth;*/
}

/**
 * 获取信用卡已出账账单
 *
 * @param creditCardAllDataList
 * @throws ParseException
 */
function getDoneBillDetail(creditCardAllData){

    try{

            var cardNum = creditCardAllData.getFullCardNum();
            var dataList = creditCardAllData.getBills();
            //倒序近11个月的日期
            for each (var transym1 in getTransymBy(11)) {
                var expenses = new ArrayList();
                var billAllData = getDoneBillAllDataHeaderData(creditCardAllData)
                // 获取信用卡表头信息
                getBillDataHeader(transym1,cardNum);
                // 解析信用卡表头信息
                // 如果最后一个月时间和未出账单时间相等，数据属于未出账单上
                addBillHeaderInfo(expenses,"DONE",billAllData,transym1);
                //抓去消费明细
                crawlBillInfo(cardNum,transym1);
                //解析消费明细
                parseBillDetailInfo(expenses , "DONE",billAllData);
                //添加到billAllData中
                billAllData.setShoppingSheets(expenses);
                //将数据添加到集合中
                //dataList.add(billAllData);
                //分期处理
                setShoppingInstallment(billAllData,expenses);
            }
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡getDoneBillDetail方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }

}

function isInLast6MonthsGetResult(transym) {
    var transym2 =  "20"+transym;
    var a ;
    var startTimeAndEndTime = getTime1();//20180402
    var start = startTimeAndEndTime[0].substring(0,6);//201808
    var end = startTimeAndEndTime[1].substring(0,6);//201802
    logger.info("输出开始时间{}和结束时间{}和当前选择的时间{}",start,end,transym2);
    //var isInLast6Months1 = yyyyMM_PARSER.parse(transym1);
    // 输出开始时间201807和结束时间201801和当前选择的时间201707
    var sdf = new SimpleDateFormat("yyyyMM");
    var start1 = sdf.parse(start);
    var  end1 = sdf.parse(end);
    var  mid1 = sdf.parse(transym2);
    if (end1.before(mid1) && start1.after(mid1)){
        a = 1;
    }else if(mid1.compareTo(start1)==0){
        a = 1;
    }else {
        a = 0;
    }
    return a;
}
function crawlBillInfo(fullCardNum,transym1) {

    var transym =  transym1.replaceAll("-","");
    var a = isInLast6MonthsGetResult(transym);
    var TransmissionTime;
    var currentTime = new Date();
    //账单日
    var billTime = context.get("billTime");
    //如果时间在账单日之前，不下载，否则，就下载
    if(currentTime.before(billTime) || currentTime.equals(billTime)){
        TransmissionTime = "1855";
    }else{
        TransmissionTime = transym;
    }
    var requestParams = new LinkedHashMap();
    var doneBilDetaillurl = "https://pbank.psbc.com/perbank/creditCardBill_billDetailDownload.do";
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("IS_BATCH_DOWN_FLAG","1");
    requestParams.put("currentBusinessCode","00841001");
    requestParams.put("accountNo",fullCardNum);
    requestParams.put("currencyFlag","L");
    requestParams.put("billTime",TransmissionTime);
    requestParams.put("isInLast6Months",a);

    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var taskey = context.get(LUA_TASK_KEY);
    var year =taskey.substring(0,2);
    var mounth =taskey.substring(2,4);
    var date =taskey.substring(4,6);
    var doneDetalFile = RequestUtil.postAsFile("D:\\htmlStorage\\BANK\\"+year+"\\"+mounth+"\\"+date+"\\"+taskey+"\\" +fullCardNum+TransmissionTime +"doneBilDetaill.xls",doneBilDetaillurl, requestParams, header);
    var doneDetalFileUrl = doneDetalFile.getPath();
    logger.info("任务【 {} 】 ,获取卡列表结果【 {} 】", context.get(LUA_TASK_KEY), doneDetalFileUrl);
    storeDataToFile(context, doneDetalFile,fullCardNum+"_"+"credit_card_Done_imfo.html");
    context.put("doneDetalFile",doneDetalFile);
}

function addBillHeaderInfo(expenses,billType,billAllData,billMonth) {
    try{
        //获取还款日，本期应还款金额，本期最低还款金额
        var newCharges = BigDecimal.ZERO;
        var billHeader = JSON.parse(context.get("billHeader"));
        logger.info("输出表头信息{}",billHeader);
        if("UNDONE".equals(billType)){
            logger.info("邮储银行taskKey = {},获取到的是未出账单",context.get(LUA_TASK_KEY), billMonth);
            billAllData.setBillId(UUID.randomUUID().toString());
            billAllData.setBillType(billType);
            billAllData.setBankName("邮储银行");
            billAllData.setBillMonth(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth)));
            billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth))+"-18"));
            logger.info("{}",billAllData.getBillDate())
            context.put("billTime",billAllData.getBillDate());
            billAllData.setPaymentDueDate(null);
            billAllData.setLastBalance(populateLastBalance());
            context.put("lastBalance", new BigDecimal(0));
            billAllData.setUsdNewBalance(null);
            billAllData.setUsdMinPayment(null);
            billAllData.setUsdLastBalance(null);
            billAllData.setLastPayment(null);
            billAllData.setUsdLastPayment(null);
            billAllData.setUsdNewCharges(null);
            billAllData.setInterest(null);
            billAllData.setUsdInterest(null);
            billAllData.setCreditLimit(context.get("creditLimit") == null ? null : new BigDecimal(context.get("creditLimit")));
            billAllData.setUsdCreditLimit(null);
            billAllData.setCashLimit(new BigDecimal(context.get("cashBalance")));
            billAllData.setUsdCashLimit(null);
            billAllData.setShoppingSheets(expenses);
        }else if(!StringUtils.equals(billHeader.getString("em"),"无该卡片的账单记录") ){
            var payment_due_date = billHeader.getString("NOW_PAY_DATE");
            var new_balance = billHeader.getString("NOW_NESS_PAY_AMT");
            var minPayment = billHeader.getString("NOW_LOW_PAY_AMT");

            billAllData.setBillId(UUID.randomUUID().toString());
            billAllData.setBillType(billType);
            billAllData.setBankName("邮储银行");//2017-06
            billAllData.setBillMonth(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth)));
            billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth))+"-18"));
            logger.info("{}",billAllData.getBillDate())
            context.put("billTime",billAllData.getBillDate());
            billAllData.setPaymentDueDate(billType.equals("UNDONE") ? null : yyyyMMdd_PARSER.parse(payment_due_date));
            billAllData.setLastBalance(populateLastBalance());
            billAllData.setNewBalance(new_balance == null ? null : new BigDecimal(new_balance));
            context.put("lastBalance",billAllData.getNewBalance());
            billAllData.setUsdNewBalance(null);
            billAllData.setUsdMinPayment(null);
            billAllData.setMinPayment(minPayment == null ? null : new BigDecimal(minPayment));
            billAllData.setUsdLastBalance(null);
            billAllData.setLastPayment(null);
            billAllData.setUsdLastPayment(null);
            billAllData.setNewCharges(context.get("new_charges"))
            billAllData.setUsdNewCharges(null);
            billAllData.setInterest(null);
            billAllData.setUsdInterest(null);
            billAllData.setCreditLimit(new BigDecimal(context.get("creditLimit")));
            billAllData.setUsdCreditLimit(null);
            billAllData.setCashLimit(new BigDecimal(context.get("cashBalance")));
            billAllData.setUsdCashLimit(null);
            billAllData.setShoppingSheets(expenses);
        }else {
            logger.info("邮储银行taskKey = {},未能获取到【{}】账单，故只保留表头",context.get(LUA_TASK_KEY), billMonth);
            billAllData.setBillId(UUID.randomUUID().toString());
            billAllData.setBillType(billType);
            billAllData.setBankName("邮储银行");
            billAllData.setBillMonth(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth)));
            billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth))+"-18"));
            logger.info("{}",billAllData.getBillDate())
            context.put("billTime",billAllData.getBillDate());
            billAllData.setPaymentDueDate(null);
            billAllData.setLastBalance(populateLastBalance());
            //billAllData.setNewBalance(finalNewBalance == null ? null : new BigDecimal(finalNewBalance));
            //本期的new_balance即为下期的last_balance
            context.put("lastBalance", new BigDecimal(0));
            billAllData.setUsdNewBalance(null);
            //billAllData.setMinPayment(finalMinPayment == null ? null : new BigDecimal(finalMinPayment));
            billAllData.setUsdMinPayment(null);
            billAllData.setUsdLastBalance(null);
            billAllData.setLastPayment(null);
            billAllData.setUsdLastPayment(null);
            // billAllData.setNewCharges(finalNewCharges.equals(BigDecimal.ZERO) ? null : finalNewCharges);
            billAllData.setUsdNewCharges(null);
            billAllData.setInterest(null);
            billAllData.setUsdInterest(null);
            billAllData.setCreditLimit(context.get("creditLimit") == null ? null : new BigDecimal(context.get("creditLimit")));
            billAllData.setUsdCreditLimit(null);
            billAllData.setCashLimit(new BigDecimal(context.get("cashBalance")));
            billAllData.setUsdCashLimit(null);
            billAllData.setShoppingSheets(expenses);
        }
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡expenseIFexist方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }

}

function setShoppingInstallment(billAllData,expenseList){
    try{
        if(expenseList==null || expenseList.size()<=0){
            return;
        }
        var freeList = new ArrayList();//手续费
        var periodList = new ArrayList();//期数
        for each(var expense in expenseList) {
            var des = expense.getDescription();//获取描述
            if(des.contains("账单分期")){
                if(des.contains("手续费")){
                    freeList.add(expense);
                }else{
                    periodList.add(expense);
                }
            }
        }

        var instList = new ArrayList();
        var countSize = freeList.size()>periodList.size()?periodList.size():freeList.size();
        for (var i = 0; i < countSize; i++) {
            var free = freeList.get(i);
            var period = periodList.get(i);
            var ins = new Installment();
            ins.setInstallmentDesc(period.getDescription().trim());//分期描述
            ins.setHandingfeeDesc(free.getDescription().trim());//分期手续费描述
            ins.setBillId(UUID.randomUUID().toString());//分期编号
            ins.setTransDate(free==null ? null:free.getTransDate());//交易时间
            ins.setPostDate(free==null ? null:free.getPostDate());//记账日期
            ins.setShoppingsheetId(UUID.randomUUID().toString());//消费记录
            ins.setInstallmentType("CONSUME");//分期类型
            ins.setTransferFee(null);//转账手续费
            var list = new ArrayList();
            ins.setAmountMoney(period.getAmountMoney());//本期金额
            //ins.setAmountMoney(free.getAmountMoney());//本期金额
            ins.setCurrencyType("CNY");//币种
            ins.setHandingFee(free==null ? new BigDecimal("0"):free.getAmountMoney());//本期手续费
            //ins.setHandingFee(free==null ? new BigDecimal("0"):period.getAmountMoney());//本期手续费
            instList.add(ins);
        }
        billAllData.setInstallments(instList);
    } catch (e) {
        logger.error("taskKey={} 分期数据抓取异常：{}", context.get(LUA_TASK_KEY), e);
        statCaughtExceptionByJS(context, e);
    }
}


function getBillDataHeader(transym1,fullCardNum) {
    var transym =  transym1.replaceAll("-","");
    var a = isInLast6MonthsGetResult(transym);
    var parament = needParameters();
    var sequenceNo = parament.getString("sequenceNo");
    var  moneyUrl = "https://pbank.psbc.com/perbank/creditCardBill_billHeaderQuery.do";
    var requestParams = new LinkedHashMap();
    requestParams.put("ec","00000000");
    requestParams.put("em","无该卡片的账单记录");
    requestParams.put("billTime",transym);
    requestParams.put("accountNo",fullCardNum);
    requestParams.put("currencyFlag","L");
    requestParams.put("sequenceNo",sequenceNo);
    requestParams.put("windowId",context.get("windowId"));
    requestParams.put("currentBusinessCode","00844001");
    requestParams.put("isInLast6Months",a);
    requestParams.put("flag","2");
    requestParams.put("mvcId",context.get("mvcId"));
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("RANDOM_ID",context.get("randomID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("channel","1101");
    requestParams.put("version","stanver");


    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var billHeader = RequestUtil.post(moneyUrl, requestParams, header);
    storeDataToFile(context, billHeader, fullCardNum+"_"+transym+"billHeader.html");
    context.put("billHeader",billHeader);
}

function setNewCharges(billAllData){
    var expenses =  billAllData.getShoppingSheets();
    var newCharges = BigDecimal.ZERO;
    for each (var expense in expenses) {
        if(expense.getAmountMoney().compareTo(BigDecimal.ZERO)>0){
            newCharges = newCharges.add(expense.getAmountMoney());
        }
    }
    billAllData.setNewCharges(newCharges.compareTo(BigDecimal.ZERO)==0 ? null : newCharges);
}
function setNewCharges(creditCardAllData){

    try{
            for (var i = 0; i <creditCardAllData.getBills().size() ; i++) {
                setNewCharges(creditCardAllData.getBills().get(i));
            }
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡setNewCharges方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }

}

/*/!**
 * 解析已出/未出账单
 *!/
 function parseBillDetailInfo(creditCardAllData,  filePath,  billMonth,  billType) {
 logger.info("当前账单类型：{}, taskKey = {}", billType, context.get(LUA_TASK_KEY));
 var currentPaymentDueDate = yyyy_MM_dd_FORMAT.format(new Date()) ;
 var newBalance = null;
 var minPayment = null;
 //判断表格路径是否存在
 if (new File(filePath).exists()) {
 var i = Java.type("java.lang.Comparable");
 var Comparable = Java.extend(i);
 var comparable = new Comparable()
 {

 compareTo:function (row) {
 return row.getLastCellNum() == 7 //一行6列
 && StringUtils.isNotBlank(row.getCell(0) !== null ? row.getCell(0).toString() : "") //当前行第一个列不为空

 ? 1 : -1; //1 符合条件 -1 不符合条件
 }
 }
 var actTrsInfoRecords = readExcelsss(filePath, comparable);
 var finalCurrentPaymentDueDate = currentPaymentDueDate;
 var expenses = new ArrayList();
 var orderIndex = 1;
 var bills = creditCardAllData.getBills();
 for each (var singleExpense in actTrsInfoRecords) {
 var expense = new Expense();

 var id = UUID.randomUUID().toString();
 var transDate = singleExpense.get(0);
 var postDate = singleExpense.get(1);
 var cardNum = singleExpense.get(2);
 var description = singleExpense.get(3);

 var currencyTypeText = singleExpense.get(6);
 var currencyType = StringUtils.isNotBlank(currencyTypeText)
 ? "人民币".equals(currencyTypeText) ? "CNY" : "USD"
 : "CNY";

 var amountMoney = singleExpense.get(5);
 var amountType = singleExpense.get(4);
 //没有该字段，取当期账单中所有amount_money正金额，金额相加，值为正数
 if (!amountType.contains("-")) {
 newCharges = newCharges.add(new BigDecimal(amountMoney));
 }

 expense.setId(id);

 //已出账账单日期包含横线 未出账账单不含横线
 if (billType.equals("UNDONE")) {
 newBalance = (newBalance == null
 ? (context.get("lastBalance") !== null ? context.get("lastBalance") : BigDecimal.ZERO).add(new BigDecimal(amountMoney))
 : new BigDecimal(newBalance).add(new BigDecimal(amountMoney))).toString();
 expense.setTransDate(yyyyMMdd_PARSER.parse(transDate));
 expense.setPostDate(yyyyMMdd_PARSER.parse(postDate));
 } else {
 expense.setTransDate(yyyy_MM_dd_PARSER.parse(transDate));
 expense.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));
 }


 expense.setCardNum(cardNum);
 expense.setDescription(description);
 expense.setCategory(getCreditCategory("PSBC", description, amountMoney));
 expense.setAmountMoney(new BigDecimal(amountMoney));
 expense.setBalance(null); //信用卡无余额
 expense.setCurrencyType(currencyType);
 expense.setOrderIndex(orderIndex);
 expense.setTransMethod("");
 expense.setNameOnOppositeCard("");
 expense.setOppositeBank("");
 expense.setOppositeCardNo("");
 expense.setTransAddr("");
 expense.setTransChannel("");
 expense.setRemark("");

 expenses.add(expense);
 orderIndex++;
 }

 var finalNewBalance = newBalance;
 var finalMinPayment = minPayment;
 var finalNewCharges = newCharges;
 //账单详情不为空
 if (listTableTR.size() > 0) {

 //分页的情况要添加到原账单月中否则添加新的账单月
 var billAllData = new BillAllData();
 billAllData.setBillId(UUID.randomUUID().toString());
 billAllData.setBillType(billType);
 billAllData.setBankName("邮储银行");

 billAllData.setBillMonth(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth)));
 billAllData.setBillDate(yy_MM_PARSER.parse(billMonth)) + "-" + ((context.get("billDay")).length() == 2 ? context.get("billDay") : "0" +context.get("billDay"));
 billAllData.setPaymentDueDate(billType.equals("UNDONE") ? null : yyyy_MM_dd_PARSER.parse(finalCurrentPaymentDueDate));
 billAllData.setLastBalance(populateLastBalance());
 billAllData.setNewBalance(finalNewBalance == null ? null : new BigDecimal(finalNewBalance));
 context.put("lastBalance", new BigDecimal(0));
 billAllData.setUsdNewBalance(null);
 billAllData.setMinPayment(finalMinPayment == null ? null : new BigDecimal(finalMinPayment));
 billAllData.setUsdMinPayment(null);
 billAllData.setUsdLastBalance(null);
 billAllData.setLastPayment(null);
 //                   .setLastPayment(populateLastPayment());
 //                    context.put("lastPayment", finalLastPayment);
 billAllData.setUsdLastPayment(null);
 billAllData.setNewCharges(finalNewCharges.equals(BigDecimal.ZERO)
 ? new BigDecimal(0) == null ? null : BigDecimal.ZERO.setScale(2)
 : finalNewCharges);
 billAllData.setUsdNewCharges(null);
 billAllData.setInterest(null);
 billAllData.setUsdInterest(null);
 billAllData.setCreditLimit(new BigDecimal(context.get("creditLimit")));
 billAllData.setUsdCreditLimit(null);
 billAllData.setCashLimit(null);
 billAllData.setUsdCashLimit(null);

 billAllData.setShoppingSheets(expenses);
 bills.add(billAllData);
 }
 } else {
 logger.info("邮储银行taskKey = {},未能获取到【{}】账单，故只保留表头",context.get(LUA_TASK_KEY), billMonth);
 var billAllData = new BillAllData();
 billAllData.setBillId(UUID.randomUUID().toString());
 billAllData.setBillType(billType);
 billAllData.setBankName("邮储银行");
 billAllData.setBillMonth(yyyy_MM_FORMAT.format(yy_MM_PARSER.parse(billMonth)));
 billAllData.setBillDate(yy_MM_PARSER.parse(billMonth)) + "-" + ((context.get("billDay")).length() == 2 ? context.get("billDay") : "0" +context.get("billDay"));
 billAllData.setPaymentDueDate(null);
 billAllData.setLastBalance(populateLastBalance());
 billAllData.setNewBalance(finalNewBalance == null ? null : new BigDecimal(finalNewBalance));
 //本期的new_balance即为下期的last_balance
 context.put("lastBalance", new BigDecimal(0));
 billAllData.setUsdNewBalance(null);
 billAllData.setMinPayment(finalMinPayment == null ? null : new BigDecimal(finalMinPayment));
 billAllData.setUsdMinPayment(null);
 billAllData.setUsdLastBalance(null);
 billAllData.setLastPayment(null);
 //               .setLastPayment(populateLastPayment());
 //               context.put("lastPayment", finalLastPayment);
 billAllData.setUsdLastPayment(null);
 billAllData.setNewCharges(finalNewCharges.equals(BigDecimal.ZERO) ? null : finalNewCharges);
 billAllData.setUsdNewCharges(null);
 billAllData.setInterest(null);
 billAllData.setUsdInterest(null);
 billAllData.setCreditLimit(context.get("creditLimit") == null ? null : new BigDecimal(context.get("creditLimit")));
 billAllData.setUsdCreditLimit(null);
 billAllData.setCashLimit(null);
 billAllData.setUsdCashLimit(null);
 billAllData.setShoppingSheets(expenses);
 bills.add(billAllData);

 }
 }*/
/**
 * 读取excel
 *
 * @throws IOException
 * @throws FileNotFoundException
 */
function readExcelsss(excelFilePath, comparable) {
    var list = new LinkedList();
    var workbook = null;
    try {
        workbook = new HSSFWorkbook(new FileInputStream(excelFilePath));
    } catch ( e) {
        //statCaughtExceptionByJS(context, e);
        return list;
    }
    //第一个Sheet页
    var sheet = workbook.getSheetAt(0);

    for (var j = sheet.getFirstRowNum(); j < sheet.getPhysicalNumberOfRows(); j++) {
        var row=sheet.getRow(j);
        if (comparable.compareTo(row) < 0) {
            continue;
        }
        var linked = new LinkedList();
        for (var k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
            var cell = row.getCell(k);
            linked.add(cell == null ? "" : cell.toString());
        }
        list.add(linked);
    }
    return list;
}
/**
 * 解析已出\未出账账单
 *
 * @param creditCardAllData 数据model
 * @param doc html文档
 * @throws ParseExceptionhh
 */
function parseBillDetailInfo( expenses ,  billType ,billAllData) {
    try{

        var filePath = context.get("doneDetalFile")
        logger.info("输出表格路径{}",filePath);

        logger.info("当前账单类型：{}, taskKey = {}", billType, context.get(LUA_TASK_KEY));
        var lastPayment = BigDecimal.ZERO ;
        if (new File(filePath).exists()) {
            var i = Java.type("java.lang.Comparable");
            var Comparable = Java.extend(i);
            var comparable = new Comparable()
            {
                compareTo:function (row) {
                    return row.getLastCellNum() == 7 //一行7列
                    && StringUtils.isNotBlank(row.getCell(0) !== null ? row.getCell(0).toString() : "") //当前行第一个列不为空
                        // hhhh
                        ? 1 : -1; //1 符合条件 -1 不符合条件
                }
            }
            var actTrsInfoRecords = readExcelsss(filePath, comparable);

            var orderIndex = 1;

            //翻转list
            if (actTrsInfoRecords.size() == 0) {
                logger.info("邮储银行在解析表格时获取到的是没有数据的表格 任务号taskKey = {}",context.get(LUA_TASK_KEY));
                return;
            }
            actTrsInfoRecords.remove(0);
            Collections.reverse(actTrsInfoRecords);
            var new_charges = BigDecimal.ZERO ;
            for each(var actTrsInfoRecord in actTrsInfoRecords){
                var expense = new Expense();
                var id = UUID.randomUUID().toString();
                var transDate = actTrsInfoRecord.get(0);
                var postDate = actTrsInfoRecord.get(1);
                var cardNum = actTrsInfoRecord.get(2);
                var description = actTrsInfoRecord.get(3);
                var currencyTypeText = actTrsInfoRecord.get(6);
                logger.info("获取的交易日期{}", currencyTypeText)
                var currencyType = StringUtils.isNotBlank(currencyTypeText)
                    ? "人民币".equals(currencyTypeText) ? "CNY" : "USD"
                    : "CNY";

                var amountMoney = actTrsInfoRecord.get(5);
                var monerliu =  actTrsInfoRecord.get(4);
                //钱的用途支出还是收入
                if(monerliu.contains("-")){
                    expense.setAmountMoney(new BigDecimal(("-"+amountMoney)));
                }else{
                    expense.setAmountMoney(new BigDecimal(amountMoney));
                    //计算new_charger
                    new_charges = new_charges.add(new BigDecimal(amountMoney))
                }

                if(description.contains("还款")){
                    lastPayment = lastPayment.add(new BigDecimal(("-"+amountMoney)));
                    logger.info("输出本期账单的所有还款金额相加{}",lastPayment);
                }
                logger.info("输出本期账单的所有+还款金额相加的值{}",new_charges);
                context.put("new_charges",new_charges);
                expense.setId(id);
                expense.setTransDate(yyyyMMdd_PARSER.parse(transDate));
                expense.setPostDate(yyyyMMdd_PARSER.parse(postDate));
                expense.setCardNum(cardNum);
                expense.setDescription(description.replace(/\s+/g, ""));
                // expense.setCategory(getCreditCategory("PSBC", description, amountMoney));
                expense.setCategory(classify( actTrsInfoRecord.get(2), expense.getAmountMoney()));
                expense.setBalance(null); //信用卡无余额
                expense.setCurrencyType(currencyType);
                expense.setOrderIndex(orderIndex);
                expense.setTransMethod("");
                expense.setNameOnOppositeCard("");
                expense.setOppositeBank("");
                expense.setOppositeCardNo("");
                expense.setTransAddr("");
                expense.setTransChannel("");
                expense.setRemark("");

                expenses.add(expense);
                orderIndex++;
            }
            billAllData.setLastPayment(!BigDecimal.ZERO.equals(lastPayment) ?  lastPayment : null);

        }
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡时parseBillDetailInfo方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }
}

function populaNewBalance(){
    var lastBalance = context.get("lastBalance");
    if(!Objects.equals(lastBalance, null) && !Objects.equals(lastBalance, BigDecimal.ZERO)) {
        return lastBalance;
    } else {
        return null;
    }
}

function populateLastBalance(){
    var lastBalance = context.get("lastBalance");
    if(!Objects.equals(lastBalance, null) && !Objects.equals(lastBalance, BigDecimal.ZERO)) {
        return lastBalance;
    } else {
        return null;
    }
}

function populateLastPayment(){
    var lastPayment = context.get("lastPayment");
    if(!Objects.equals(lastPayment, null) && !Objects.equals(lastPayment, BigDecimal.ZERO)) {
        return lastPayment;
    } else {
        return null;
    }
}

/**
 * 找到存在的账单月 用于分页时将账单明细合并到已存在的账单月
 *
 * @param transym 账单月
 * @param bills 账单集合
 * @return
 */
function findExistBillMonth( transym,  bills) {
    var tempBillAllData = null;
    for each (var bill in bills) {
        if(bill.getBillMonth().contains(transym)) {
            tempBillAllData = bill;
        }
    }
    return tempBillAllData;
}

/**
 * 信用卡明细信息
 *
 * @param creditCardAllDataList
 */
function getCreditCardDetailInfoList( creditCardAllDataList) {

    try{
        for each (var creditCardAllData in creditCardAllDataList) {
            //抓取基本信息信息
            crawlCreditDepostInfo(creditCardAllData.getFullCardNum());
            //解析基本信息信息
            praseCreditBaseInfo(creditCardAllData);
        }
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡时getCreditCardDetailInfoList方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }


}
function praseCreditBaseInfo(creditCardAllData) {

    //获取信用卡基本信息，比如额度，卡号
    var depostInfo = JSON.parse(context.get("baseListHtml"));
    //判断不为空进行抓取
    if(depostInfo==""&&depostInfo==null){
        return ;
    }
    //持卡人姓名
    var nameOnCard = depostInfo.getString("CARDNHOLDNAME").replaceAll("先生","").trim();
    logger.info("获取的信用卡名字是{}",nameOnCard);
    //信用卡额度
    var creditLimit = depostInfo.getString("creditLimit").trim();
    context.put("creditLimit", creditLimit);
    //信用卡可用余额
    var balance = depostInfo.getString("AVLIMT").trim();
    //信用卡现金可用额度
    var cashBalance = depostInfo.getString("CshAmt").trim();
    context.put("cashBalance", cashBalance);

    var cshCredVlu = depostInfo.getString("CshCredVlu").trim();

    //获取当前的年份201818
    var billDay = depostInfo.getString("CYCL_NBR").trim();
    logger.info("输出当前的年份{}",billDay);
    context.put("billDay", billDay);

    var cardId = UUID.randomUUID().toString();
    creditCardAllData.setCardId(cardId);
    creditCardAllData.setNameOnCard(nameOnCard);
    creditCardAllData.setCreditLimit(new BigDecimal(creditLimit));
    creditCardAllData.setBalance(new BigDecimal(balance));
    creditCardAllData.setCashBalance(new BigDecimal(cashBalance));
    creditCardAllData.setCashLimit(new BigDecimal(cshCredVlu));

}
/**
 * 获取信用卡
 */
function  crawlCreditDepostInfo (creditCardAllData) {
    var cardNum =creditCardAllData.getFullCardNum();
    logger.info("输出卡号{}",cardNum);
    var  cardDetailInfoUrl = "https://pbank.psbc.com/perbank/creditCardAcctQuery_queryHostDetail.do";
    var requestParams = new LinkedHashMap();
    requestParams.put("currentBusinessCode","00841001");
    requestParams.put("accountNo",cardNum);
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("RANDOM_ID",context.get("randomID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("channel","1101");
    requestParams.put("version","stanver");


    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var baseListHtml = RequestUtil.post(cardDetailInfoUrl, requestParams, header);
    storeDataToFile(context, baseListHtml, "credit_"+cardNum+"_card_detail_info.html");
    context.put("baseListHtml",baseListHtml)
}
/**
 * 循环遍历12
 * @returns {ArrayList}
 */
function twelveMonth(){

    var calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    // calendar.add(Calendar.YEAR,-2);
    var simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    var map = new HashMap();
    var list = new ArrayList();
    for (var i = 0; i < 12; i ++) {

        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 1);
        var start = simpleDateFormat.format(calendar.getTime());
        calendar.add(Calendar.MONTH, -1);
        var  end = simpleDateFormat.format(calendar.getTime());
        map.put("start", start);
        map.put("end",end );
        //map.put("startDate", startDate);
        list.add(map);
    }
    return list;
}
/**
 *
 */
function getTime1() {

    var date = DateUtil.date();
    var endDateStr = (DateUtil.format(date, "yyyy-MM-dd")).replaceAll("-","");


    var  st4 = DateUtil.offset(date, DateField.MONTH, -6);
    var  ss = DateUtil.offset(st4, DateField.DAY_OF_MONTH, 1);
    var midDateStr = (DateUtil.format(ss, "yyyy-MM-dd")).replaceAll("-","");

    /*  //var quarterStartTimeAndDeadline = new ArrayList();20171230
     //当前时间
     var calendar = Calendar.getInstance();
     var endDate = calendar.getTime(); //截止日期上限
     var endDateStr = yyyy_MM_dd_FORMAT.format(endDate).replaceAll("-","");

     calendar.add(Calendar.MONTH, -6);
     calendar.add(Calendar.DAY_OF_MONTH, 1);
     var midDate = calendar.getTime();
     var midDateStr = yyyy_MM_dd_FORMAT.format(midDate).replaceAll("-","");//中间6个月日期
     logger.info("输出end{}和mid{}",endDateStr,midDateStr)
     */

    return [endDateStr,midDateStr];
}

/**
 * 从指定时间到今天为止，获取时间最长为6个月的时间，能查询的范围是一年
 * @param fromDate 起始时间
 * @return
 */
function getTime() {

    //当前时间
    var calendar = Calendar.getInstance();//12
    var endDate = calendar.getTime(); //截止日期上限
    var endDateStr = yyyy_MM_dd_FORMAT.format(endDate).replaceAll("-","");
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),endDateStr);



    calendar.add(Calendar.MONTH, -2);//10
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    var midDate = calendar.getTime();
    var endDateStr1 = yyyy_MM_dd_FORMAT.format(midDate).replaceAll("-","");//8个月之前
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),endDateStr1);

    calendar.add(Calendar.MONTH, -1);//9
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    var midDate = calendar.getTime();
    var endDateStr2 = yyyy_MM_dd_FORMAT.format(midDate).replaceAll("-","");//8个月之前
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),endDateStr2);


    calendar.add(Calendar.MONTH, -2);//7
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    var midDate = calendar.getTime();
    var endDateStr3 = yyyy_MM_dd_FORMAT.format(midDate).replaceAll("-","");//8个月之前
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),endDateStr3);




    calendar.add(Calendar.MONTH, -1);//6
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    var midDate1 = calendar.getTime();
    var midDateStr1 = yyyy_MM_dd_FORMAT.format(midDate1).replaceAll("-","");//4个月之前
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),midDateStr1);


    calendar.add(Calendar.MONTH, -2);//4
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    var midDate = calendar.getTime();
    var midDateStr2 = yyyy_MM_dd_FORMAT.format(midDate).replaceAll("-","");//8个月之前
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),midDateStr2);


    calendar.add(Calendar.MONTH, -1);//3
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    var midDate = calendar.getTime();
    var midDateStr = yyyy_MM_dd_FORMAT.format(midDate).replaceAll("-","");//8个月之前
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),midDateStr);


    calendar.add(Calendar.MONTH, -2);
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    var startLimit = calendar.getTime();
    var startDateStr = yyyy_MM_dd_FORMAT.format(startLimit).replaceAll("-","");;//12个月之前
    logger.info("任务号 taskKey 【{} 】 输出时间{}",context.get(LUA_TASK_KEY),startDateStr);
    //1-3 ,4-6, 7-9,10-12
    return [[startDateStr,midDateStr],[midDateStr2,midDateStr1],[endDateStr3,endDateStr2] ,[endDateStr1,endDateStr]];
}

/**
 * 按照设定月数 n 获取n个yy-mm格式的日期
 *
 * @return
 * @param monthCount
 */
function getTransymBy( monthCount){

    var dateString;
    var date = DateUtil.date();//10
    var billDate = DateUtil.parse(DateUtil.format(date,"yyyy-MM")+"-"+context.get("billDay")+" 22:00:00","yyyy-MM-dd HH:mm:ss");
    var transymList = new ArrayList();
    for(var   i = 0; i<12 ;i++){
        date = DateUtil.offset(date, DateField.MONTH, -1);
        dateString = DateUtil.format(date, "yy-MM");
        if(date.after(billDate)){
            date =  DateUtil.beginOfMonth(DateUtil.nextMonth());
        }
        transymList.add(dateString);
    }

    Collections.reverse(transymList);
    logger.info("transymList集合的值{}",transymList);
    return transymList;

    /* var  date = DateUtil.date();
     var  dateString ;
     /!*if(date.after(DateUtil.parse((DateUtil.format(date, "yyyy_MM")+"-"+context.get("billDay")+"22:00:00"),"yyyy_MM_dd_HH_mm_ss"))){
     DateUtil.nextMonth();
     }*!/
     var transymList = new ArrayList();
     for(var  i = 0; i<12 ;i++){
     dateString = DateUtil.format(date, "yy_MM");
     transymList.add(dateString);
     date = DateUtil.offset(date, DateField.MONTH, -1);
     }

     Collections.reverse(transymList);
     logger.info("输出时间{}",transymList);
     return transymList;*/

    /* var  date = DateUtil.date();
     var  dateString ;
     /!*!/!*if(date.after(DateUtil.parse((DateUtil.format(date, "yyyy_MM")+"-"+context.get("billDay")+"22:00:00"),"yyyy_MM_dd_HH_mm_ss"))){
     DateUtil.nextMonth();
     }*!/!*!/
     var billDate = DateUtil.parse(DateUtil.format(time,"yyyy-MM")+"-"+context.get("billDay")+"22:00:00",yyyy_MM_dd_HH_mm_ss);
     if()
     var transymList = new ArrayList();
     for(var  i = 0; i<12 ;i++){
     dateString = DateUtil.format(date, "yy_MM");
     transymList.add(dateString);
     date = DateUtil.offset(date, DateField.MONTH, -1);
     }

     Collections.reverse(transymList);
     logger.info("输出时间{}",transymList);
     return transymList;
     */
    /* var calendar = Calendar.getInstance();
     var dateString;
     //当前日期在账单日之后则先对日期月份加1
     var  yy_MM_FORMAT = new SimpleDateFormat("yy-MM");
     if (calendar.getTime().after(yyyy_MM_dd_HH_mm_ss_PARSER.parse(yyyy_MM_FORMAT.format(calendar.getTime()) + "-" + context.get("billDay") + " 22:00:00"))) {
     calendar.add(Calendar.MONTH, 1);
     }
     var transymList = new ArrayList();
     calendar.get(Calendar.MONTH);
     transymList.add(yy_MM_FORMAT.format(calendar.getTime()));
     for (var i = 0; i < monthCount; i++) {
     calendar.add(Calendar.MONTH, -1);
     dateString = yy_MM_FORMAT.format(calendar.getTime());
     transymList.add(dateString);
     }
     Collections.reverse(transymList);
     logger.info("输出所有的时间{}",transymList);
     return transymList;
     */

}

/**
 * 获取信用卡基本信息
 *
 * @param creditCardAllDataList
 */
function getCreditCardInfoList( creditCardAllData) {

    try{
        //获取到卡列表
        var cardList = JSON.parse(context.get("cardList"));
        //获取到卡列表数据
        var cardNumList =  cardList.getJSONArray("iAccountInfoList");
        //将卡列表进行循环并抓取基本信息
        for each (var element in cardNumList) {
            var  accountType = element.getString("accountType");
            if(!("07").equals(accountType)){
                continue;
            }
            //var creditCardAllData = new CreditCardAllData();
            var cardNum = element.getString("accountNo");
            logger.info("叔叔从{}",cardNum);
            context.put("cardNum",cardNum);
            creditCardAllData.setFullCardNum(cardNum);
            creditCardAllData.setCardNum(cardNum.substring(cardNum.length() - 4, cardNum.length()));
            creditCardAllData.setCardType("信用卡");
            creditCardAllData.setBankName("邮储银行");
            //creditCardAllData.setBills(new ArrayList());
           // creditCardAllDataList.add(creditCardAllData);
        }
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取信用卡时getCreditCardInfoList方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }

}

/**
 * 借记卡抓取
 *
 * @throws Exception
 */
function debitCrawl(creditCardAllData) {

    try{
        //var creditCardAllDataList = new ArrayList();
        //获取借记卡基本信息
        getDebitCardInfoList(creditCardAllData);

        getDebitCardDetailInfo(creditCardAllData);

        crawlAndPraseDebitBillInfo(creditCardAllData);

        /*//是否存在借记卡
        if (creditCardAllDataList.size() > 0) {
            //获取借记卡详细信息

            if(creditCardAllDataList.size() > 0) {
                //获取借记卡账单信息
                for each (var creditCardAllData in creditCardAllDataList) {
                    //下载并解析每个月数据
                    crawlAndPraseDebitBillInfo(creditCardAllData);
                }
            }else{
                logger.info("没有可用借记卡，taskKey={}", context.get(LUA_TASK_KEY));
                unExistDebit = true;
            }
            context.put("debit_data", creditCardAllDataList);
        } else {
            logger.info("没有借记卡，taskKey={}", context.get(LUA_TASK_KEY));
            unExistDebit = true;
        }*/
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取借记卡debitCrawl方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }


}

function getOpenBank(openOrg,index) {

    var getOpenBankUrl = "https://pbank.psbc.com/perbank/queryBranch.do";
    var requestParams = new HashMap();
    requestParams.put("branchNo",openOrg);//"openOrg":"11008108",
    requestParams.put("currentBusinessCode","00311000");
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("RANDOM_ID",context.get("randomID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("channel","1101");
    requestParams.put("version","stanver");


    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var cardBillInfoQueryHtml = RequestUtil.post(getOpenBankUrl, requestParams, header);
    storeDataToFile(context, cardBillInfoQueryHtml, index+"openbank_list.html")
    var bankName = JSON.parse(cardBillInfoQueryHtml).getString("branchName");
    logger.info("邮储银行 taskKey={}，获取的开户银行是{}", context.get(LUA_TASK_KEY),bankName);
    context.put("openBankName",bankName);
}



function crawlAndPraseDebitBillInfo(creditCardAllData) {
    
    var time = DateUtil.date();//10
    var next2Month =  DateUtil.beginOfMonth(DateUtil.offset(DateUtil.nextMonth(), DateField.MONTH, 1));
    var nextMonth =  DateUtil.beginOfMonth(DateUtil.nextMonth());
    var cardNum = creditCardAllData.getFullCardNum();
    var dataList = creditCardAllData.getBills();
    for (var i = 0; i <12 ; i++) {
        //获取的是下一个月
        next2Month  = DateUtil.beginOfMonth(DateUtil.offset(next2Month, DateField.MONTH, -1));
        var start = DateUtil.format(next2Month,"yyyyMMdd");

        //获取的是本月
        nextMonth  = DateUtil.offset(nextMonth, DateField.MONTH, -1);
        var end = DateUtil.format(nextMonth,"yyyyMMdd");
        var allExpense = new ArrayList();
        //var billAllDate = new BillAllData();
        var billAllDate = getDoneBillAllDataHeaderData(creditCardAllData);
        logger.info("开始时间start{} 和结束时间{}",start,end);
        var end1 = end.substring(0,4)+"-"+end.substring(4,6)+"-"+end.substring(6);
        var end2 = end1.replaceAll("-","").substring(0,6);
        logger.info("sudf{}",end2);
        var depoitSdf = new SimpleDateFormat("yyyy-MM-dd");
        var open_time = creditCardAllData.getOpenTime();
        var open_time1 = (yyyy_MM_dd_FORMAT.format(open_time)).replaceAll("-","").substring(0,6);
        var open_time2 = (yyyy_MM_dd_FORMAT.format(open_time)).replaceAll("-","");
        //只有年月比较，如果是同年同月，接着比较日期，如果日期在开卡时间之后，那就让开卡时间作为开始时间。
        if(depoitSdf.parse(end1).before(open_time) &&  end2.equals(open_time1)){
            logger.info("邮储银行，任务号taskKey = {}输出开始时间start{}和结束时间{}",context.get(LUA_TASK_KEY),start,end);
            //补充表头信息
            debitExpenseIFexist(open_time2,billAllDate);
            //下载明细数据
            detaiDown(open_time2,start,cardNum);
            //解析明细数据
            parserDebitBillInfo(creditCardAllData,allExpense);

        }else if (depoitSdf.parse(end1).before(open_time)) {
            continue;
        }else {
            logger.info("邮储银行，任务号taskKey = {}输出开始时间start{}和结束时间{}",context.get(LUA_TASK_KEY),start,end);
            //补充表头信息
            debitExpenseIFexist(end,billAllDate);
            //下载明细数据
            detaiDown(end,start,cardNum);
            //解析明细数据
            parserDebitBillInfo(creditCardAllData,allExpense);
        }
        billAllDate.setShoppingSheets(allExpense);
        //dataList.add(billAllDate);
    }




    /*var cardNum = creditCardAllData.getFullCardNum();
     var dataList = creditCardAllData.getBills();
     var calendar = Calendar.getInstance();
     calendar.setTime(new Date());
     var simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
     for (var i = 0; i < 12; i ++) {
     //11
     calendar.set(Calendar.DAY_OF_MONTH, 1);
     calendar.add(Calendar.MONTH, 1);
     var start = simpleDateFormat.format(calendar.getTime());
     //10
     calendar.add(Calendar.MONTH, -1);
     var  end = simpleDateFormat.format(calendar.getTime());

     var allExpense = new ArrayList();
     var billAllDate = new BillAllData();
     logger.info("开始时间start{} 和结束时间{}",start,end);
     var end1 = end.substring(0,4)+"-"+end.substring(4,6)+"-"+end.substring(6);
     var end2 = end1.replaceAll("-","").substring(0,6);
     logger.info("sudf{}",end2);
     var depoitSdf = new SimpleDateFormat("yyyy-MM-dd");
     var open_time = creditCardAllData.getOpenTime();
     var open_time1 = (yyyy_MM_dd_FORMAT.format(open_time)).replaceAll("-","").substring(0,6);
     var open_time2 = (yyyy_MM_dd_FORMAT.format(open_time)).replaceAll("-","");
     //只有年月比较，如果是同年同月，接着比较日期，如果日期在开卡时间之后，那就让开卡时间作为开始时间。
     if(depoitSdf.parse(end1).before(open_time) &&  end2.equals(open_time1)){
     logger.info("邮储银行，任务号taskKey = {}输出开始时间start{}和结束时间{}",context.get(LUA_TASK_KEY),start,end);
     //补充表头信息
     debitExpenseIFexist(open_time2,billAllDate);
     //下载明细数据
     detaiDown(open_time2,start,cardNum);
     //解析明细数据
     parserDebitBillInfo(creditCardAllData,allExpense);

     }else if (depoitSdf.parse(end1).before(open_time)) {
     continue;
     }else {
     logger.info("邮储银行，任务号taskKey = {}输出开始时间start{}和结束时间{}",context.get(LUA_TASK_KEY),start,end);
     //补充表头信息
     debitExpenseIFexist(end,billAllDate);
     //下载明细数据
     detaiDown(end,start,cardNum);
     //解析明细数据
     parserDebitBillInfo(creditCardAllData,allExpense);
     }
     billAllDate.setShoppingSheets(allExpense);
     dataList.add(billAllDate);
     calendar.add(Calendar.MONTH, -1);
     }*/
}
function debitExpenseIFexist(billMonth,billAllDate) {
    try{
        var billMonth1 = billMonth.substring(0,4)+"-"+billMonth.substring(4,6)+"-01";
        billAllDate.setBillId(UUID.randomUUID().toString());
        billAllDate.setBillType("");
        billAllDate.setBankName("邮储银行");
        billAllDate.setBillMonth(billMonth1.substring(0,7));
        billAllDate.setBillDate(yyyy_MM_PARSER.parse(billMonth1));
        billAllDate.setPaymentDueDate(null);
        billAllDate.setNewBalance(null);
        billAllDate.setUsdNewBalance(null);
        billAllDate.setMinPayment(null);
        billAllDate.setUsdMinPayment(null);
        billAllDate.setLastBalance(null);
        billAllDate.setUsdLastBalance(null);
        billAllDate.setLastPayment(null);
        billAllDate.setUsdLastPayment(null);
        billAllDate.setNewCharges(null);
        billAllDate.setUsdNewCharges(null);
        billAllDate.setInterest(null);
        billAllDate.setUsdInterest(null);
        billAllDate.setCreditLimit(null);
        billAllDate.setUsdCreditLimit(null);
        billAllDate.setCashLimit(null);
        billAllDate.setUsdCashLimit(null);
    }
    catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取借记卡时debitExpenseIFexist方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }
}


function parserDebitBillInfo(creditCardAllData,allExpense){
    try{

        var path = context.get("billDownUrl");
        logger.info("邮储银行开始解析账单明细：taskKey = {}", context.get(LUA_TASK_KEY));
        //判断路径是否存在
        if (new File(path).exists()) {
            var i = Java.type("java.lang.Comparable");
            var Comparable = Java.extend(i);
            var comparable = new Comparable(){
                compareTo:function(row) {
                    return row.getLastCellNum() == 9 //一行9列
                    && StringUtils.isNotBlank(row.getCell(0) !== null ? row.getCell(0).toString() : "") //当前行第一个列不为空
                        // && !"流水号".equals(row.getCell(0) !== null ? row.getCell(0).toString() : "") //第一列不为流水号
                        ? 1 : -1; //1 符合条件 -1 不符合条件
                }
            }
            var actTrsInfoRecords = readExcelsss(path, comparable);

            var orderIndex = 1;
            //翻转list
            if (actTrsInfoRecords.size() == 0) {
                logger.info("邮储银行在解析表格时获取到的是没有数据的表格 任务号taskKey = {}",context.get(LUA_TASK_KEY));
                return;
            }
            //翻转list
            actTrsInfoRecords.remove(0);
            Collections.reverse(actTrsInfoRecords);
            for each (var actTrsInfoRecord in actTrsInfoRecords) {
                var expense = new Expense();
                expense.setId(UUID.randomUUID().toString());
                expense.setDescription(actTrsInfoRecord.get(2));
                var description = actTrsInfoRecord.get(6);
                if(description.equals("支出")){
                    if(actTrsInfoRecord.get(7).equals("0.00")){
                        expense.setAmountMoney(new BigDecimal(actTrsInfoRecord.get(7)));
                    }
                    expense.setAmountMoney(new BigDecimal(actTrsInfoRecord.get(7).replaceAll(",","")));
                }else{
                    if(actTrsInfoRecord.get(7).equals("0.00")){
                        expense.setAmountMoney(new BigDecimal(actTrsInfoRecord.get(7)));
                    }
                    var amount_money = "-"+actTrsInfoRecord.get(7).replaceAll(",","");
                    expense.setAmountMoney(new BigDecimal(amount_money));
                }
                expense.setBalance(new BigDecimal(actTrsInfoRecord.get(8).replaceAll(",","")));
                var cardNum = creditCardAllData.getFullCardNum();
                expense.setCardNum(cardNum.substring(cardNum.length() - 4, cardNum.length()));
                expense.setCategory(classify( actTrsInfoRecord.get(2), expense.getAmountMoney()));
                /*if((actTrsInfoRecord.get(6)).contains("支出")){
                 expense.setCategory( CategoryUtil.getDebitCategory(actTrsInfoRecord.get(2),actTrsInfoRecord.get(6).replaceAll(",","")));
                 }else{
                 expense.setCategory(CategoryUtil.getDebitCategory(actTrsInfoRecord.get(2),"-" + actTrsInfoRecord.get(6).replaceAll(",","")));
                 }*/
                expense.setCurrencyType("CNY");
                var transDate = yyyyMMdd_PARSER.parse(actTrsInfoRecord.get(1).replaceAll("-",""))
                expense.setTransDate(transDate);
                var postDate = actTrsInfoRecord.get(1);
                expense.setPostDate(yyyy_MM_dd_PARSER.parse(postDate));
                expense.setTransAddr("");
                expense.setNameOnOppositeCard("");
                expense.setOppositeBank("");
                expense.setOppositeCardNo("");
                expense.setTransMethod("");
                expense.setTransChannel("");
                expense.setRemark("");
                expense.setOrderIndex(orderIndex);

                allExpense.add(expense);
                orderIndex++;

            }
        }

    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取借记卡时parserDebitBillInfo方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }

    //}
}

function getNextBillMonth( billMonth){
    var sdf = new SimpleDateFormat("yyyy-MM");
    var billDate = sdf.parse(billMonth);
    var cal = Calendar.getInstance();
    cal.setTime(billDate);
    cal.add(Calendar.MONTH, 1);
    billMonth = sdf.format(cal.getTime());
    return billMonth;
}


function createBlankBillAllData( creditCardAllData,  startMonth){
    var billAllData = new BillAllData();
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBillType("");
    billAllData.setBankName("邮储银行");
    billAllData.setBillMonth(startMonth);
    billAllData.setBillDate(yyyy_MM_PARSER.parse(startMonth));
    billAllData.setPaymentDueDate(null);
    billAllData.setNewBalance(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setMinPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setLastBalance(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setLastPayment(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setNewCharges(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setInterest(null);
    billAllData.setUsdInterest(null);
    billAllData.setCreditLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setCashLimit(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setShoppingSheets(new ArrayList());
    creditCardAllData.getBills().add(billAllData);
}

function getStartMonth( openTime){
    var map = new HashMap();
    var now = Calendar.getInstance();
    now.add(Calendar.YEAR,-1);
    var date = now.getTime();
    var today = new Date();
    var sdf = new SimpleDateFormat("yyyy-MM");
    var currentMonth = sdf.format(date);
    var endMonth = sdf.format(today);
    if(openTime!=null) {
        currentMonth = currentMonth.compareTo(yyyy_MM_dd_PARSER.format(openTime))>0?currentMonth:yyyy_MM_dd_PARSER.format(openTime).substring(0, 7);
    }

    var no = getMonthSpace(currentMonth,endMonth);
    map.put("currentMonth",currentMonth);
    map.put("monthNo",no);
    return map;

}
function getMonthSpace( date1,  date2) {
    var result = 0;
    var year1 = date1.substring(0,4);
    var month1 = date1.substring(5,7);
    var year2 = date2.substring(0,4);
    var month2 = date2.substring(5,7);
    if(year2.compareTo(year1)==0){
        result = Integer.parseInt(month2)-Integer.parseInt(month1)+1;
    }else{
        result = Integer.parseInt(month2)-Integer.parseInt(month1)+11;
    }
    return result;

}



/**
 * 获取的queryString是没有问号的
 *
 * @param queryStringMap
 * @param isUrlEncoding
 * @return
 * @throws UnsupportedEncodingException
 */
function getQueryStringFromMap(queryStringMap,  isUrlEncoding){
    var sbuffer = new StringBuffer();
    for each (var key in queryStringMap.keySet()){
        var value= queryStringMap.get(key);
        if(!StringUtils.isBlank(value)){
            queryStringMap.put(key, value);
        }
        sbuffer.append(key).append("=").append(value).append("&");
    }
    var value = sbuffer.toString().replaceAll("&$", "");
    if(isUrlEncoding){
        value = URLEncoder.encode(value, "utf8");
    }
    return value;
}

/**
 * 获取签约借记卡详细信息 含开卡时间 余额
 *
 * @param creditCardAllDataList
 * @throws ParseException
 */
function getDebitCardDetailInfo(creditCardAllData){
    try{

        var baseInfoHtml = get_html2();
        storeDataToFile(context, baseInfoHtml, "baseInfo.html");

        //获取存款信息页面
        var depostListHtml = context.get("depostListHtml");

        var depostList = JSON.parse(depostListHtml);
        logger.info("{}",depostList);

        //查询借记卡 账户余额 可用余额 开卡时间 获取活期信息
        //初始化存储类型数据
        //creditCardAllData.setDeposits(new ArrayList());

        if(depostList!=null && !StringUtils.equals("系统错,请联系主机",depostList.getString("em"))) {
            //解析存款信息
            praseDepositsInfo(depostList,creditCardAllData);

        }else if(StringUtils.equals("账户不存在或销户",depostList.getString("em"))){
            logger.info("该账户不存在或者是销户，任务号{}，卡号{}",context.get(LUA_TASK_KEY),cardNum);

        }else{
            logger.error("邮储银行 taskKey:{} 解析存款类型时发生异常：",context.get(LUA_TASK_KEY),e);
            throw new BankException(BALO_99601_40 ,"解析存款类时发生异常");
        }

       /* var baseInfoHtml = get_html2();
        storeDataToFile(context, baseInfoHtml, "baseInfo.html");
        var it = creditCardAllDataList.iterator();
        while(it.hasNext()){

            var creditCardAllData = it.next();
            var cardNum = creditCardAllData.getFullCardNum();

            //抓取存款信息
            crawlDepositstInfo(cardNum);

            //获取存款信息页面
            var depostListHtml = context.get("depostListHtml");

            var depostList = JSON.parse(depostListHtml);
            logger.info("{}",depostList);

            //查询借记卡 账户余额 可用余额 开卡时间 获取活期信息
            //初始化存储类型数据
            creditCardAllData.setDeposits(new ArrayList());
            if(depostList!=null && !StringUtils.equals("系统错,请联系主机",depostList.getString("em"))) {

                //解析存款信息
                praseDepositsInfo(depostList,creditCardAllData);


            }else if(StringUtils.equals("账户不存在或销户",depostList.getString("em"))){
                logger.info("该账户不存在或者是销户，任务号{}，卡号{}",context.get(LUA_TASK_KEY),cardNum);
                continue;
            }else{
                logger.error("邮储银行 taskKey:{} 解析存款类型时发生异常：",context.get(LUA_TASK_KEY),e);
                throw new BankException(BALO_99601_40 ,"解析存款类时发生异常");
            }

        }*/
        //统一计算balance
        sumBalance(creditCardAllData);

    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取借记卡时getDebitCardDetailInfo方法异常{}", context.get(LUA_TASK_KEY), e);
    }


    //其他类型存储信息获取 整存整取
    /*var depositsInfoTrs = doc.select(".listTable:nth-of-type(2) tr.trValue");
     for each (var tr in depositsInfoTrs) {
     var tds = tr.select("td");
     if (tds.size() == 8) {
     var balance = tds.eq(0).text()==null?"0":tds.eq(0).text();
     var depositType = tds.eq(1).text();
     var period = tds.eq(2).text();
     var dueDate = tds.eq(3).text();
     var depositDate = tds.eq(4).text();
     var creditCardTimeDeposit = new CreditCardTimeDeposit();
     //金额
     creditCardTimeDeposit.setBalance(new BigDecimal(balance));
     //币种
     creditCardTimeDeposit.setCurrencyType(currencyTypeMappings.get("人民币"));
     //存款类型
     creditCardTimeDeposit.setDepositType(depositType);
     //利率
     creditCardTimeDeposit.setInterest(new BigDecimal((interestMappings.get(depositType)).get(period)));
     //计息日
     creditCardTimeDeposit.setDepositDate(yyyyMMdd_PARSER.parse(dueDate));
     //到期日
     if(depositDate!="") {
     creditCardTimeDeposit.setDueDate(yyyyMMdd_PARSER.parse(depositDate));
     }
     //存期
     creditCardTimeDeposit.setPeriod(period2NumberMappings.get(period.substring(0, 1)));
     //存期单元
     creditCardTimeDeposit.setPeriodUnit(periodUnit2EnglishMappings.get(period.substring(period.length()-1, period.length())));
     creditCardAllData.getDeposits().add(creditCardTimeDeposit);
     }

     }*/


}

function sumBalance(creditCardAllData) {
    var balance = BigDecimal.ZERO;
    for each (var creditCardTimeDeposit in creditCardAllData.getDeposits()) {
        balance = balance.add(creditCardTimeDeposit.getBalance());
    }
    creditCardAllData.setBalance(balance);
}

function praseDepositsInfo(creditCardAllData) {
    //获取存款信息页面
    //获取存款信息页面
    var depostListHtml = context.get("depostListHtml");

    var depostList = JSON.parse(depostListHtml);
    logger.info("{}",depostList);

    if(depostList!=null && !StringUtils.equals("系统错,请联系主机",depostList.getString("em"))) {
        //解析存款信息
        var balance = depostList.getString("balance");
        logger.info("邮储银行 taskkey: {},获取的余额是{}", context.get(LUA_TASK_KEY), balance);
        var openTime = depostList.getString("openDate");
        context.put("openTime", openTime);
        logger.info("邮储银行 taskkey: {} 获取的时间是{}", context.get(LUA_TASK_KEY), openTime);
        var depositList = new ArrayList();
        var deposits = new CreditCardTimeDeposit();
        deposits.setBalance(new BigDecimal(balance));
        deposits.setCurrencyType("CNY");
        //deposits.setInterest(new BigDecimal(interestMappings.get("活期")));
        deposits.setDepositType("活期");
        deposits.setDepositDate(yyyyMMdd_PARSER.parse(openTime));
        deposits.setDueDate(null);
        deposits.setPeriod(null);
        deposits.setPeriodUnit("");
        depositList.add(deposits);
        //数据构造

        creditCardAllData.setCashBalance(null);
        creditCardAllData.setCashLimit(null);
        creditCardAllData.setCreditLimit(null);
        creditCardAllData.setOpenTime(yyyyMMdd_PARSER.parse(openTime));
        creditCardAllData.setDeposits(depositList);

    }else if(StringUtils.equals("账户不存在或销户",depostList.getString("em"))){
        logger.info("该账户不存在或者是销户，任务号{}，卡号{}",context.get(LUA_TASK_KEY),cardNum);

    }else{
        logger.error("邮储银行 taskKey:{} 解析存款类型时发生异常：",context.get(LUA_TASK_KEY),e);
        throw new BankException(BALO_99601_40 ,"解析存款类时发生异常");
    }

    sumBalance(creditCardAllData);
    
}

function crawlDepositstInfo(creditCardAllData) {
    var cardNum = creditCardAllData.getFullCardNum();
    logger.info("输出卡号{}",cardNum);
    var  cardDetailInfoUrl = "https://pbank.psbc.com/perbank/queryBHQSubAcc.do";
    var requestParams = new LinkedHashMap();
    requestParams.put("accNo",cardNum);
    requestParams.put("pwdFlag","0");
    requestParams.put("bkBookFlg","2");
    requestParams.put("currentBusinessCode","00311000");
    requestParams.put("EMP_SID",context.get("empSID"));
    requestParams.put("RANDOM_ID",context.get("randomID"));
    requestParams.put("responseFormat","JSON");
    requestParams.put("channel","1101");
    requestParams.put("version","stanver");


    var header = new LinkedHashMap();
    header.put("Cookie", context.get("cookies"));
    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko");

    var depostListHtml = RequestUtil.post(cardDetailInfoUrl, requestParams, header);
    storeDataToFile(context, depostListHtml, "debit_card_detail_info_" + cardNum + ".html");
    context.put("depostListHtml",depostListHtml);
}

/**
 * 获取借记卡列表信息
 *
 * @param creditCardAllDataList
 */
function getDebitCardInfoList(creditCardAllData) {

    try{
        var cardList = JSON.parse(context.get("cardList"));
        var cardNumList =  cardList.getJSONArray("iAccountInfoList");
        var username  = JSON.parse(getNameOnCard());
        var usernameOnCard1 = username.getString("data1").replaceAll("您好,","").trim();
        var usernameOnCard = usernameOnCard1.replaceAll("您好，","").trim();
        logger.info("邮储银行 taskKey:{}获取姓名{}",context.get(LUA_TASK_KEY),usernameOnCard);
        //获取到借记卡的列表
        var index =1;
        for each (var element in cardNumList) {
            var  accountType = element.getString("accountType");
            if(("07").equals(accountType)){
                continue;
            }
            getOpenBank(element.getString("openOrg"),index);
            var bankName = context.get("openBankName");
            logger.info("邮储银行 taskKey={}，获取的开户银行是{}", context.get(LUA_TASK_KEY),bankName);
            var fullCardNumber = element.getString("accountNo");
            logger.info("邮储任务号taskKey = {},卡号:{}",context.get(LUA_TASK_KEY),fullCardNumber);
            context.put("accountNo",fullCardNumber);
           // creditCardAllData.setCardId(UUID.randomUUID().toString());
            creditCardAllData.setFullCardNum(fullCardNumber);
            creditCardAllData.setCardNum(fullCardNumber.length() > 4 ? fullCardNumber.substring(fullCardNumber.length() - 4, fullCardNumber.length()) : "");
            creditCardAllData.setBankName("邮储银行");
            creditCardAllData.setCardType("借记卡");
            creditCardAllData.setNameOnCard(usernameOnCard);
            creditCardAllData.setOpenBank(bankName);
            creditCardAllData.setNameOnCard(usernameOnCard);
            index++;
            //creditCardAllDataList.add(creditCardAllData);
        }
        logger.info("邮储银行借记卡个数：{}，taskKey:{}", cardNumList.size() ,context.get(LUA_TASK_KEY));
    } catch (e){
        statCaughtExceptionByJS(context, e);
        logger.error("任务taskKey = {}, 抓取借记卡getDebitCardInfoList方法发生异常{}", context.get(LUA_TASK_KEY), e);
    }

}

function getName() {
    var getBackBaseData = getNameOnCard();
    var username  = JSON.parse(getBackBaseData);
    logger.info("邮储银行 taskKey:{}获取姓名{}",context.get(LUA_TASK_KEY),username);
    var usernameOnCard = username.getString("data1").replaceAll("您好,","").trim();
    var username = usernameOnCard.replaceAll("您好，","").trim();
    logger.info("邮储银行 taskKey:{}获取姓名{}",context.get(LUA_TASK_KEY),username);
    context.put("usernameOnCard",username);
}


